最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add an onload event to window - Stack Overflow

programmeradmin0浏览0评论

My code is,

<html>
    <head>
       <title>onclick test</title>
       <script type="text/javascript">
           var googleWindow = window.open('');
           window.onload = change;
           function change(){
            alert('Hello');
           }
        </script>
</html>

The above code is working fine. It calls the change function when the window is loading. I am trying add onload event to the googleWindow but it is not working.

<html>
    <head>
       <title>onclick test</title>
       <script type="text/javascript">
           var googleWindow = window.open('');
           googleWindow.onload = change;
           function change(){
            alert("Hello');
           }
        </script>
</html>

How do i add an event to the googleWindow?

Thanks,

My code is,

<html>
    <head>
       <title>onclick test</title>
       <script type="text/javascript">
           var googleWindow = window.open('http://www.google.');
           window.onload = change;
           function change(){
            alert('Hello');
           }
        </script>
</html>

The above code is working fine. It calls the change function when the window is loading. I am trying add onload event to the googleWindow but it is not working.

<html>
    <head>
       <title>onclick test</title>
       <script type="text/javascript">
           var googleWindow = window.open('http://www.google.');
           googleWindow.onload = change;
           function change(){
            alert("Hello');
           }
        </script>
</html>

How do i add an event to the googleWindow?

Thanks,

Share Improve this question asked Jan 26, 2013 at 12:47 user2008774user2008774 131 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

You cannot add an event to a window in another domain.

The onload event only triggers a function that is loaded in that window, so you can't really do that. However, if you can control the content of the new window you're opening (i.e. if you'd open a window that displays some content of your own) then you could place an onload handler in the page that opens in that window, and then the called function could interact with the opener window via 'window.opener', e.g. if you have two files '1.html' and '2.html' then you can have:

1.html

<a href="#" onClick="window.open('2.html')">Open '2.html'</a>

2.html

<head><script>
window.opener.alert("this alert is displayed by the '1.html' window");
</script></head>

In the above, after you click the link in the first window, the second window will open (probably in a new tab in your browser) and immediately after it gets opened you'll see the alert displayed in the first window (i.e. the first tab)

PS
Oh, and as Rory pointed out in his answer, you must absolutely have the files on the same domain

发布评论

评论列表(0)

  1. 暂无评论