-1

I am trying to transfer click event from a page to another page using javascript. I have a div with a click event on page A and this is the div

HTML:

<div class="play">Play Sound</div>
<div class="pause">Stop Sound</div>

Then on page B I have a script file intended to receive the click of the div from page A. Is there a way how can I make it in such a way that if I click the div on page A let the script event on page B be called within the same application

Javascript:

$(document).ready(function() {
   var audioElement = document.createElement('audio');
       audioElement.setAttribute('src', 'audio.mp3');
       audioElement.setAttribute('autoplay', 'autoplay');
       // audioElement.load()

   $.get();

   audioElement.addEventListener("load", function() {
       audioElement.play();
   }, true);

   $('.play').click(function() {
       audioElement.play();
   });

   $('.pause').click(function() {
      audioElement.pause();
   });
});
Martin Jinda
  • 458
  • 9
  • 25

2 Answers2

0

you can use socket or local storage. local storage fires an event when other tabs makes changes. check this answer Javascript; communication between tabs/windows with same origin

Community
  • 1
  • 1
altcatalin
  • 11
  • 3
0

To transfer a click event from a page to another page using JavaScript you can use a shared worker (used in my answer) or a service worker. A shared worker is a program that runs in the background and can communicate with different pages. It is shared between pages.

The requirement to use a shared worker are; it must be served from a secure connection (https or localhost), and the target browser must support the shared worker APIs

An example to solve your problem:

a.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Page A</title>
  </head>
  <body>
    <h1>Page A with controls</h1>

    <button id="play">Play Sound</button>
    <button id="pause">Stop Sound</button>
    <a href="b.html" target="_blank">Open page B</a>

  </body>
  <script src="a.js"></script>
</html>

a.js

(function () {
    const ME = "A";
    if (!window.SharedWorker) {
        console.log("window.SharedWorker not available");
        return;
    }
    const playButtonElement = document.getElementById("play");
    const pauseButtonElement = document.getElementById("pause");

    const sharedWorker = new SharedWorker("sharedworker.js", "audio");

    playButtonElement.addEventListener("click", function (event) {
        sharedWorker.port.postMessage({
            from: ME,
            play: true
        });
    }, false);

    pauseButtonElement.addEventListener("click", function (event) {
        sharedWorker.port.postMessage({
            from: ME,
            play: false
        });
    }, false);

    sharedWorker.port.onmessage = function(event) {
        ;//do nothing here
    };

    sharedWorker.port.start();

    sharedWorker.port.postMessage({
        from: ME,
        start: true
    });
}());

b.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Page B</title>
  </head>
  <body>
    <h1>Page B with audio element</h1>

  </body>

  <script src="b.js"></script>
</html>

b.js

(function () {
    const ME = "B";
    if (!window.SharedWorker) {
        console.log("window.SharedWorker not available");
        return;
    }

    const audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'audio.mp3');
    audioElement.setAttribute('autoplay', 'autoplay');
    // audioElement.load()
    document.body.appendChild(audioElement); // useful ?


    audioElement.addEventListener("load", function() {
        audioElement.play();
    }, true);


    const sharedWorker = new SharedWorker("sharedworker.js", "audio");
    sharedWorker.port.onmessage = function(event) {
        const messageObject = event.data
        console.log("received", messageObject);
        if (messageObject.hasOwnProperty("play")) {
            if (messageObject.play) {
                audioElement.play();
            } else {
                audioElement.pause();
            }
        }
    };

    sharedWorker.port.start();

    sharedWorker.port.postMessage({
        from: ME,
        start: true
    });
}());

sharedworker.js

//sharedworker.js
/*assuming we open page  a first, page b second*/
const A = "A";
const B = "B";

let portA;
let portB;
self.addEventListener("connect", function(connectEvent) {

    const port = connectEvent.ports[0];
    port.addEventListener("message", function(event) {
        const data = event.data;
        if (data.start) {
            if (data.from === A) {
                portA = port;
            } else {
                portB = port;
            }
        } else {
            console.log(data);
            portB.postMessage(data);//relay message
        }
        console.log(`Shared worker memory report
portA, portB: ${portA}, ${portB}`);
    });

   port.start();

}, false);

Not provided here, but needed to try the example: A server program to serve static files, audio.mp3

Also see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers and https://developer.mozilla.org/en/docs/Web/API/SharedWorker

Walle Cyril
  • 2,691
  • 2
  • 16
  • 46