【问题标题】:How do I take text contained in web page and make it part of the page title?如何获取网页中包含的文本并将其作为页面标题的一部分?
【发布时间】:2019-11-16 06:30:49
【问题描述】:

我在编写 Tampermonkey/Greasemonkey 脚本时急需帮助,该脚本获取网页中的部分信息并使其成为页面(和窗口)标题的一部分。

客户名称是目标(内部)网页的一部分,并在 HTML 中明确标记:

<div id="patient-info" class="ehr-patients-info">
    <div id="patient-identification">
        <span title="" id="patient-name">
            Johnnyfirst

            Smithylast
        </span>
    </div>
... 

我想将文本“Johnnyfirst Smithylast”添加到窗口标题并尝试:

var ptname = document.getElementById("patient-name") ;
document.title = document.title + " | Name: " + ptname ;

但这导致标题如下:...| Name: null

第二个问题是我搭载此用户脚本的网站不会一次全部加载。在初始页面加载之后,有大量的 javascript 功能会加载页面的各个部分并最终显示如上所示的客户端名称。

当我尝试$(window).on('load', function() { ... })$(document).ready() 时,它似乎在作用于尚未完全加载信息的网页的初步版本。

【问题讨论】:

    标签: tampermonkey userscripts greasemonkey-4


    【解决方案1】:

    您的目标页面是 AJAX 驱动的和Greasemonkey/Tampermonkey fires way before most AJAX page loads finish。所以,你必须使用MutationObserverwaitForKeyElements等技术来弥补。

    例如,这是一个完整的 Tampermonkey 脚本,它会在找到 patient-name 节点时更改标题:

    // ==UserScript==
    // @name     _Put the patient Name in the title
    // @match    *://YOUR_SERVER.COM/YOUR_PATH/*
    // @noframes
    // @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // @grant    GM.getValue
    // ==/UserScript==
    // @grant    none
    //- The @grant directives are needed to restore the proper sandbox.
    /* global waitForKeyElements */
    /* eslint-disable no-multi-spaces, curly */
    'use strict';
    
    waitForKeyElements ("#patient-name, .patient-name", scrapeTextToTitle);
    
    function scrapeTextToTitle (jNode) {
        var nameRaw         = jNode.text ().trim ();
        var nameSanitized   = nameRaw.replace (/\s+/g, " ");
        document.title     += " | Name: " + nameSanitized;
    }
    

    【讨论】:

    • 感谢您的快速回复!我注意到你是 waitForKeyElements 的作者,但我做梦也没想到会收到 Brock Adams 本人的回复!谢谢您的帮助。有机会我会试试的。 // 也感谢您编辑我的帖子;我试图在简短和解释我的动机之间取得平衡,这样我就不会收到诸如“你为什么要那样做?就那样做吧……”这样的回答。
    • 谢谢你,@Brock!在某些情况下,您的解决方案似乎有效。其他情况我注意到患者姓名在网页中是这样表示的:&lt;h3 class="patient-name ng-binding"&gt;Johnnyfirst Smithylast&lt;/h3&gt; 在您的代码中,患者姓名前面有“#”。这是否意味着在标签中查找“id=”?是否有其他字符表示在标签中查找“class=”,例如“class=患者名称 ng-binding”?
    • 听起来我应该找到类的后代节点而不是 id,如 &lt;h3 class="patient-name ng-binding"&gt;。如果我提供 iframeSelector,我看到您的 waitForKeyElements() 函数已经这样做了。如何指定 iframeSelector?该网站似乎使用 iframe,但我可以使用 Firefox 的内置检查器看到代码中没有实际的 &lt;iframe&gt; 标签。如何找到有关 iframe 的信息并将其传递给您的 Tampermonkey 脚本?有没有办法说“将整个文档视为您的 iframe”,以便搜索整个内容?
    • @kwantum,查看更新的答案和参考api.jquery.com/category/selectors
    • 在我看来你还不需要对 iframe 做任何特别的事情。但如果需要,这里有很多问答。
    猜你喜欢
    • 2020-12-22
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多