如何检测 Firefox 插件中的选项卡是否已更改或刷新

问题描述 投票:0回答:1

救命!! 这是我的 javascript 文件中的内容,我不知道为什么它不起作用。我正在尝试在刷新和选项卡更改时设置背景图像。背景的改变似乎有效,但其他部分却无效。任何事情都有帮助。谢谢

browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // Check if the tab is the active tab and if its status has changed to "complete"
  if (tab.active && changeInfo.status === "complete") {
    // Tab has been refreshed, do something here
    if (isBackgroundOn == true) {
      toggleBgButton.textContent = "Turn Background Off";
      changeBackground();
    } else {
      toggleBgButton.textContent = "Turn Background On";
      changeBackground();
    }
  } else {
    if (isBackgroundOn == true) {
      toggleBgButton.textContent = "Turn Background Off";
      changeBackground();
    } else {
      toggleBgButton.textContent = "Turn Background On";
      changeBackground();
    }
  }
});



function changeBackground() {
   browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
      // Execute the content script that will change the background image
     browser.tabs.executeScript(tabs[0].id, {
        code: `
       document.body.style.backgroundImage = 'url("https://picsum.photos/1440/900")';
        `
      });
    });
  }

这就是我的清单文件中的内容

{
    "manifest_version": 2,
    "name": "custom chess.com themes",
    "version": "1.0",
    "description": "personilize your chess.com theme",
    "icons": {
      "48": "icons/icon48.png"
    },
    "browser_action": {
      "default_icon": "icons/icon48.png",
      "default_popup": "popup.html"
    },
    "permissions": [
      "storage",
      "activeTab"
    ],
    "browser_specific_settings": {
      "gecko": {
        "id": "[email protected]",
        "strict_min_version": "42.0"
      }
    },
    "background": {
      "scripts": ["assets/js/popup.js"],
      "persistent": true
    }
  }
   
javascript firefox-addon firefox-addon-sdk
1个回答
0
投票
use database or localstorage. 
let tabId as key, the you want change attribute as value.
eg: clicked.

when the Listener detect the first time tab is complete. 
if clicked is false, execute script. 
click button, update the clicked to true.

after click the button, sendmessage to runtime update the clicked to true, the tab is reload or refresh.

the Listener detect again, 
now the clicked is true.

you can type your code in here ( if(clicked === true)).
my code is working for me.



/**
* button click, then update database. clicked => true
*/
async function useAssignDoWhat(tabId, assign) {
  await browser.scripting.executeScript({
    target: {tabId},
    args: [assign],
    func: async function (message) {
      
      let {tabId} = message
      // todo button click
      /**
       * 
       * @type {HTMLButtonElement}
       */
      let elementBtn = document.querySelector(`#btnred`)
      elementBtn.click();
      // todo runtime send message, update database => clicked => true
      await browser.runtime.sendMessage({
        sid: tabId,
        objNew: {clicked: true},
        act: `actDaoUpdateSearchtbl`
      })
    }
  })
}

async function tabNew(args) {
  let {url} = args;
  let tabId = await browser.tabs.create({url})
  let sid = tabId;

  /**
   *
   * @param tabId{ number}
   * @param changeInfo{ browser.tabs._OnUpdatedChangeInfo}
   * @param tab{ browser.tabs.Tab}
   * @return {Promise<void>}
   */
  let cbOnUpdated = async (
    tabId,
    changeInfo,
    tab) => {

    if (tab.status.includes('complete')) {
      try {
        // todo query entity from database by table key
        let searchone = await daoSearchtblQueryOne({sid});
        // todo if clicked === false, execute script
        if (searchone.clicked === false) {
          await new Promise(res => setTimeout(res, 6 * 100));
          let detailUrl = tab.url;
          const target = Object.assign({}, args, {tabId, detailUrl, url});
          await useAssignDoWhat(tabId, target);
        }
        // todo if clicked === true, the tab is reload or refresh.
        
        else {
          handlePrintConsole({
            from: `tabNew cbOnUpdated`,
            info: `clicked === true`,
          })

          // todo detect the tab is reload or refresh!!!
          // type your code in here

        }
      } catch (e) {
      } finally {
        // browser.tabs.onUpdated.removeListener(cbOnUpdated);
      }
    }

  };
  /**
   *
   * @type { browser.tabs.UpdateFilter}
   */
  let filterOnUpdated = {
    tabId,
    properties: [
      'status',
      'url',
    ],
  };
  if (browser.tabs.onUpdated.hasListener(cbOnUpdated) === false) {
    browser.tabs.onUpdated.addListener(cbOnUpdated, filterOnUpdated);
  }
  
}
© www.soinside.com 2019 - 2024. All rights reserved.