Apply a Greasemonkey/Tampermonkey/userscript to an iframe?

UpIX picture UpIX · Jun 3, 2016 · Viewed 12.8k times · Source

The title is pretty much the question:

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

If so, how?

Thank you.

Answer

Brock Adams picture Brock Adams · Jun 4, 2016

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.