Apply a Greasemonkey/Tampermonkey/userscript to an iframe?

前端 未结 3 1614
误落风尘
误落风尘 2020-11-30 07:44

The title is pretty much the question:

Is it possible to add a Greasemonkey script to an iframed website?

If so, how?

Thank you.

3条回答
  •  醉酒成梦
    2020-11-30 08:07

    This is a solution for cases where the iframe has no location to trigger @include or @match.

    This works with Greasemonkey 4.

    We must wait for each frame to be loaded before we can operate on it. I do this by using waitForKeyElements.js, which waits for elements matching a given CSS selector, just like looping through the matches in document.querySelectorAll("selector"), and then applies a given function to the response:

    // ==UserScript==
    // @include https://blah.example.com/*
    // @require https://git.io/waitForKeyElements.js
    // ==/UserScript==
    
    function main(where) {
      // do stuff here with  where  instead of  document
      // e.g. use  where.querySelector()  in place of  document.querySelector()
      // and add stylesheets with  where.head.appendChild(stylesheet)
    }
    
    main(document); // run it on the top level document (as normal)
    
    waitForKeyElements("iframe, frame", function(elem) {
      elem.removeAttribute("wfke_found"); // cheat wfke's been_there, use our own
      for (let f=0; f < frames.length; f++) {
        if (!frames[f].document.body.getAttribute("been_there")) {
    
          main(frames[f].document);
    
          frames[f].document.body.setAttribute("been_there", 1);
        }
      }
    });
    

    Note that the selected element is just a placeholder indicating that an iframe has loaded. We remove the "been there" tracker from waitForKeyElements because the frame may be loaded again later (we can't just use that iframe because its contents are loaded elsewhere).

    When we know a frame has loaded, we loop through each frame and look for our marker, an HTML attribute in the frame's body called been_there (like ). If it is missing, we can run our main() function on the frame's document. When we're done, we add the been_there attribute so we don't get triggered again.

提交回复
热议问题