Apply a Greasemonkey/Tampermonkey/userscript to an

2019-01-09 12:09发布

The title is pretty much the question:

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

If so, how?

Thank you.

2条回答
可以哭但决不认输i
2楼-- · 2019-01-09 12:49

Note that if you're making a chrome extension for your userscript, you also need to add "all_frames": true to your manifest or your extension won't work on iframes.

Example:

"content_scripts": [
    {
      "matches": ["*://*/*"],
      "all_frames": true,
      "js":["dont.js"],
      "run_at":"document_start"
    }
  ]
查看更多
老娘就宠你
3楼-- · 2019-01-09 13:03

In Greasemonkey (And Tampermonkey and most userscript engines) a script will fire on an iframe automatically if it meets the @include, @exclude, and/or @match directives.
And, a popular question is how to stop Greasemonkey from firing on iframes.

So, if your script had a match like:

@match https://fiddle.jshell.net/*

It would fire on jsFiddle "output" pages whether or not they appeared in an iframe.


If you wanted to fire on a JUST iframed content:

Then you would check the window.self property.
For example, suppose you had a target page like:

<body>
    <h1>I'm some webpage, either same-domain or not.</h1>
    <iframe src="//domain_B.com/somePath/somePage.htm">
...

Then you could use a script like:

// ==UserScript==
// @name    _Fires specially on domain_B.com iframes
// @match   *://domain_B.com/somePath/*
// ==/UserScript==

if (window.top === window.self) {
    //--- Script is on domain_B.com when/if it is the MAIN PAGE.
}
else {
    //--- Script is on domain_B.com when/if it is IN AN IFRAME.
    // DO YOUR STUFF HERE.
}

Important:

With the release of Greasemonkey 4, iframes handling is severely crippled (and many other things are broken, besides).
It still works properly with Tampermonkey, Violentmonkey and just about every other userscript engine.
It is strongly recommended (including by Greasemonkey itself) that you do not use Greasemonkey 4 or later.

查看更多
登录 后发表回答