Reputation: 79
I would like to run javascript in the context of the parent (to the iframe) window. I have a full control on the iframe content, but cannot directly load scripts in parent window.
Use Case: Parent page contains menu items, and based on the menu selection it loads an iframe content. I need to load a script in the iframe and execute it in context of the parent window so it keeps alive/persistent even if I navigate our of the iframe. Same domain.
DOM Script injection works, but I'm wondering if there is a better solution.
Upvotes: 3
Views: 2200
Reputation: 461
Not sure if this solution faces any limitations in your case. Try to load JS script in your iframed content:
<script src="iframed.js"></script>
and inside of iframed.js
:
// call function with context of parent window, and pass window and document as parameters.
foo.call(window.parent, window.parent, window.parent.document);
function foo(window, document) {
// now you can access all globals from the main window:
var target = document.getElementsByTagName('iframe');
// logs collection of iframes from the main window:
console.log('iframes from main window:', target);
// global context is main window
console.log('global context: ', this);
}
Upvotes: 1