首页 > 解决方案 > 多次实例化的扩展模式窗口

问题描述

每次单击扩展程序图标时,我都会在网页正文中附加一个模式窗口,但是当我这样做时,扩展程序会多次实例化,因此我从内容脚本发送的事件也会多次发送。这就是我将模态附加到正文的方式:后台脚本:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.sendMessage(tab.id, { message: 'load' });
});

内容脚本监听器:

chrome.runtime.onMessage.addListener(function(request, sender, callback) {
  main();
});

主功能 :

function main() {
  // eslint-disable-next-line no-undef
  const extensionOrigin = 'chrome-extension://' + chrome.runtime.id;
  // eslint-disable-next-line no-restricted-globals
  if (!location.ancestorOrigins.contains(extensionOrigin)) {
    // Fetch the local React index.html page
    // eslint-disable-next-line no-undef
    fetch(chrome.runtime.getURL('index.html') /*, options */)
      .then((response) => response.text())
      .then((html) => {
        const styleStashHTML = html.replace(/\/static\//g, `${extensionOrigin}/static/`);
        // eslint-disable-next-line no-undef
        $(styleStashHTML).appendTo('body');
      })
      .catch((error) => {
        console.warn(error);
      });
  }
}

有没有办法检查扩展是否已附加到正文,这样我从内容脚本发布的消息不会被多次触发?

标签: javascriptgoogle-chrome-extension

解决方案


推荐阅读