Reputation:
Want to run javascript function from parent window in child window
Example
I have to different websites let's say site1.com
and site2.com
I want from site1.com
to open new window of URL site2.com
new_window = window.open("site2.com/index.php", "window2");
Then i want to run a js function test()
on this new_window.
// Where site2.com/index.php
<html>
......
</html>
<script>
function test(){
// some code here
}
</script>
Summary
Want to open new window (child) and run some JS functions from parent window.
Upvotes: 2
Views: 786
Reputation: 74204
You can use cross document messaging to circumvent the same origin policy as follows.
Parent window (site1.com
):
var site2 = window.open("http://site2.com");
site2.postMessage("test", "http://site2.com");
Child window (site2.com
):
function test() {
// some 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 is a simple example. You could make it more sophisticated to allow callbacks, return values, etc. but that would require a blog post to be fully explained.
You may read more about window.postMessage
on the Mozilla Developer Network.
Note however that the following example will not work in Internet Explorer (obviously).
Upvotes: 4
Reputation: 3783
You can't, you have to run your function from the child window if it's not on the same domain for security reasons.
Upvotes: 0