How do I take text contained in web page and make it part of the page title?

♀尐吖头ヾ 提交于 2021-01-28 12:23:16

问题


I desperately need help with writing a Tampermonkey/Greasemonkey script that takes part of the information within the web page and makes it part of the page (and window) title.

A client's name is part of the target (internal) web page, and clearly labeled within the HTML:

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

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

I want to add the text "Johnnyfirst Smithylast" to the window title and tried:

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

But that resulted in titles like: ...| Name: null.

The second problem is that the web site to which I am piggybacking this userscript doesn't load all at once. After the initial page load, there's heavy javascript functionality which loads various parts of the page and ends up displaying the client name as above.

When I try $(window).on('load', function() { ... }) or $(document).ready(), it seems to be acting on a preliminary version of the web page that doesn't have the information fully loaded yet.


回答1:


Your target page is AJAX driven and Greasemonkey/Tampermonkey fires way before most AJAX page loads finish. So, you must use techniques like MutationObserver, waitForKeyElements, etc., to compensate.

For example, here's a complete Tampermonkey script that changes the title when it finds the patient-name node:

// ==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;
}


来源:https://stackoverflow.com/questions/56906165/how-do-i-take-text-contained-in-web-page-and-make-it-part-of-the-page-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!