I’m trying to use a Chrome userscript or a Tampermonkey script to modify a page with this structure:
<body>
content up here
<iframe id="main" src="foo.dat"></iframe>
</body>
The iframe is same-origin.
I need to access a function that’s in iframe#main. I thought I could use unsafeWindow to get it but I keep getting nothing or undefined returned.
I’ve tried a slew of things:
-
Tried creating a new script element in the
iframe, but it attaches to the parent even with$('frame#main').contents().append(script)or$('frame#main').contents()[0].createElement('script') -
window.frames["#main"].contentWindowreturns undefined.
I have tried many other things I can’t recall at the moment, but I have exhausted all my ideas and feel that I’m typing rubbish more than anything that counts.
I can’t figure out how to play with the unsafeWindow of the iFrame.
unsafeWindowdoesn’t play nice with frames/iframes on Chrome, Tampermonkey, or Firefox.@include,@exclude, and/or@matchrequirements.So, you need to account for the multiple script runs and then you have two basic approaches, depending on what you are trying to accomplish. You can:
(A) Tailor the script to specific frame(s), as in this answer.
or (B) inject your JS and use the special
framesobject to grab the specific function you want.The following script demonstrates both. Install it in Tampermonkey1 (or Firefox Greasemonkey), and then visit this test page at jsBin.
You will see that the script runs a function from both the main page and from the iframe. The console output (Tampermonkey) will be:
1 It will also work as a straight-up Chrome userscript if you remove the
unsafeWindowline(s).