Can the mechanism that loads the worker in Shared Web Workers be modified?

丶灬走出姿态 提交于 2019-11-27 09:37:49

What are you trying to achieve using SharedWorker?

to pass messages between pages from the same domain without having to set a constant interval to check if a local storage variable had changed.

You can use storage event to communicate messages between tabs at same origin

At index.html

<!DOCTYPE html>
<html>

  <head>
  </head>

  <body>
    <a href="b.html" target="_blank">open b.html</a>
    <textarea></textarea>
    <button>click</button>
    <script>
      var messages = [];
      var button = document.querySelector("button");
      var textarea = document.querySelector("textarea");
      window.addEventListener("storage", function(e) {
        console.log(e.newValue, JSON.parse(localStorage.getItem("messages")));

      });
      button.addEventListener("click", function() {
        messages.push(textarea.value);
        localStorage.setItem("messages", JSON.stringify(messages));
        localStorage.setItem("message", textarea.value);
        textarea.value = "";
      })
    </script>
    </body>
</html>

b.html

<!DOCTYPE html>
<html>

  <head>
  </head>

  <body>
    <textarea></textarea>
    <button>click</button>

    <script>
    var messages = JSON.parse(localStorage.getItem("messages"));
      window.addEventListener("storage", function(e) {
        console.log(e.newValue, JSON.parse(localStorage.getItem("messages")));
      });
      var button = document.querySelector("button");
      var textarea = document.querySelector("textarea");
      button.addEventListener("click", function() {
        messages.push(textarea.value);
        localStorage.setItem("message", textarea.value);
        localStorage.setItem("messages", JSON.stringify(messages));
        textarea.value = "";
      })
    </script>
    </body>
</html>

plnkr http://plnkr.co/edit/4nR7Rpu4zXSgTR831vQW?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!