javascript - Run JS function from parent window in child window? -
want run javascript function parent window in child window
example
i have different websites let's site1.com
, site2.com
i want site1.com
open new window of url site2.com
new_window = window.open("site2.com/index.php", "window2");
then want run js function test()
on new_window.
// site2.com/index.php <html> ...... </html> <script> function test(){ // code here } </script>
summary
want open new window (child) , run js functions parent window.
you can use cross document messaging circumvent same origin policy follows.
parent window (site1.com
):
var site2 = window.open("http://site2.com"); site2.postmessage("test", "http://site2.com");
child window (site2.com
):
function test() { // code here } window.addeventlistener("message", function (event) { if (event.origin === "http://site1.com") { var funct = window[event.data]; if (typeof funct === "function") funct(); } }, false);
this simple example. make more sophisticated allow callbacks, return values, etc. require blog post explained.
you may read more window.postmessage
on mozilla developer network.
note following example not work in internet explorer (obviously).
Comments
Post a Comment