简体   繁体   中英

How to run a child window java script function in parent window after changing the url in the parent window?

I want to execute the java script function of a child window on parent window, Even after changing the URL in the parent window. I tried like below:

**Parent.html:**

<html>
  <head>
    <title>Parent window document</title>
  </head>
  <body>
  <script type="text/Javascript">
    function openChildWindow()
    {
      var s_url     = "child.html";
      var s_name    = "ChildWindowDocument";
      var s_specs   = "resizable=yes,scrollbars=yes,toolbar=0,status=0";
      var childWnd  = window.open(s_url, s_name, s_specs);
      var div       = childWnd.document.getElementById("child_wnd_doc_div_id");
      div.innerHTML = "Hello from parent wnd dddsfds";
    }
  </script>
  <input type="button" value="Open child window document" name="sss" onclick="openChildWindow()" />
    <div>Click me: nothing will happen.</div>
    <div id="aaa" class="yourclass">
        <p>This is a paragraph with a <span>span</span> where the paragraph's container has the class. Click the span or the paragraph and see what happens.</p>
        This sentence is directly in the div with the class rather than in child element.
    </div>
    <div>Nothing for this div.</div>
    <a>dsfsd</a>
  </body>
</html>

**child.html:**

<html>
  <head>
    <title>Parent window document</title>
    <script>
    opener.document.body.onclick = function(e) {
    var sender = (e && e.target) || (window.parent.event && window.parent.event.srcElement);
    document.getElementById("id").value=sender.tagName;
    }
    </script>
  </head>
  <body>
    <div id="child_wnd_doc_div_id">child window</div>
    ID: <input type="text" id="id"/><br/>
    Name: <input type="text" id="id"/><br/>
    Xpath: <input type="text" id="id"/><br/>
    CSS: <input type="text" id="id"/><br/>
  </body>
</html>

Clearly, my concept is: I want to execute the child window function after changing the url in the parent window.

The only way I see:

observe the unload-event of the opener. When it fires, try(after a short timeout) to reassign the onclick-function(and also the onunlad-function).

Of course this will only work when both documents are placed under the same domain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM