Search code examples
javascriptjquerypopupwindow

Get value from new popup window by clicking on an element using Jquery


I want to get value from a new popup window by event clicking on an element on the new popup. My code is working the first time after I clicked on my button. After I reload the page on the new popup window my code does not work.

Index.html

<button id="open-new-windows">TEST</button>

<script>
  $("#open-new-windows").click(function () {
    var w = window.open(
      "http://localhost/test/child.html",
      "TEST",
      "width=300,height=400"
    );

    w.addEventListener("load", function () {
      var html = $(w.document.body).find("ul");
      console.log(html.length); // return 1
      html.on("click", "li", function () {
        var a = $(this).text();
        alert(a);
      });
    });
  });
</script>

Child.html

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
</ul>

enter image description here

I want to get a value after the page is loaded again. Please Help Me. Thanks.


Solution

  • My suggestion is to move the LI's click listener to the child.html and start a communication using Broadcast Channel API:

    index.html

    <button id="open-new-windows">TEST</button>
    
    <script>
        const el = (sel, par = document) => par.querySelector(sel);
    
        el("#open-new-windows").addEventListener("click", (ev) => {
            window.open("http://localhost:3000/child.html", "TEST", "width=300,height=400");
        });
    
        const bc = new BroadcastChannel("comm");
    
        bc.addEventListener("message", (ev) => {
            // Do nothing if message is not from the expected origin:
            if ( ! /^http:\/\/localhost/.test(ev.origin)) return;
            // All OK: do something with the sent message:
            alert(ev.data);
        });
    </script>
    

    child.html

    <ul>
        <li>This is LI 1</li>
        <li>This is LI 2</li>
        <li>This is LI 3</li>
        <li>This is LI 4</li>
        <li>This is LI 5</li>
        <li>This is LI 6</li>
        <li>This is LI 7</li>
    </ul>
    
    <script>
        const els = (sel, par = document) => par.querySelectorAll(sel);
    
        const bc = new BroadcastChannel("comm");
    
        const sendMessage = (ev) => {
            const elLI = ev.currentTarget;
            const text = elLI.textContent;
            bc.postMessage( text );
        };
    
        els("ul li").forEach(elLI => elLI.addEventListener("click", sendMessage) );
    </script>
    

    This way, even if you refresh the child.html page, it will attach again to the same broadcasting channel.
    See here for another example

    PS:
    edit the above's http://localhost:3000/child.html to match your configuration.