views:

394

answers:

1

I'm wondering if you can have Greasemonkey execute against an iframe only and not it's parent window. The parent window is domain A, the iframe is domain B, and the include in the script would be @include http://domain-B.com/path/*.

I don't need any interaction with the parent. I've tried this a couple of times without success. Is there any cross-domain restriction preventing someone to execute against the iframe?

PS: The iframe has JS code that prevents it from loading as the top window.

+2  A: 

Well, it's certainly possible to get Greasemonkey to run against an iframe -- in fact, it's a common question to determine how to stop it from executing on iframes as well as the main page. You should be able to take the converse of that answer to prevent code from executing on the top window:

if (window.top == window.self)  //don't run on the top window
    return;
//rest of the actual executing code goes here

I've tested it and you can use @include to match domain B (the domain of the iframe) and run a piece of arbitrary code that modifies it. I ran the following test userscript on a test page and it successfully hides the Google logo (only when Google is in an iframe).

// @include  http://www.google.com*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

if (window.top == window.self)  //don't run on top window
    return;

alert('running on a frame');

$('img').each(function() {
  $(this).hide();
});

So far as I can tell, there aren't any cross-domain restrictions involved here. I'm not sure what happens if the iframe isn't present when the page is first loaded (which is when Greasemonkey runs).

npdoty
domain-b never executes is the problem because of cross-domain restrictions in the browser. Do to cross-domain restrictions and no access to the source on domain-b I can not read DIV's to determine if something exists. I was hoping that the @include domain-b would trigger on the iframe (which is domain-b) and therefore I would have access to the markup via the GM script. I will continue to explore various approaches.
nopuck4you
Well, it worked for me: I can get a Greasemonkey script to execute on a 3rd-party domain `iframe` when I `@include` just the `iframe` domain. I've updated my answer with sample code and a test page to try it on.
npdoty