Question

I don't know why, but my greasemonkey/tampermonkey script refuses to run on pages that have an iframe. The script runs inside the iframe, but not on the root domain. If I use the @noframes option, nothing happens at all on pages with an iframe.

I've even resorted to // @match http://*/*

My test code is very simple...

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';

document.getElementsByTagName('head')[0].appendChild(script)

var title = $('title').html();
alert(title);

This will show an alert with the name of the iframe, but not the actual site. I've tried it in both greasemonkey and tampermonkey.

Was it helpful?

Solution

  1. Your target parent page may not have an actual <head> element, causing that script-instance to crash.

  2. That is not how you add jQuery with a script! You will have all manner of timing issues and code conflicts.
    See the second part of this answer for the best cross-platform way to add jQuery (But overkill if you just use GM/TM). And this bit for resolving jQuery conflicts and crashes in GM/TM scripts.

    It may be that the iframes load jQuery on their own, or you just have a happy timing accident (for now), but don't rely on such luck for your code.

  3. The script metadata section / header is crucial for questions like this. Your question needs to show the whole script.
    The errors from the Browser Console and a link to the target page would not be amiss either.

If the script is for Tampermonkey/Greasemonkey (no plain Chrome), this will work:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
var title = $('title').html();
alert(title);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top