how do I detect if the tab has changed or refreshed in a firefox addon

86 Views Asked by At

help!! this is what i have in my javascript file and i am not sure why it is not working. i am trying to set a background image on refresh and tab change. the changing of the background seems to work but the other part does not. anything helps. thanks

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")';
        `
      });
    });
  }

this is what i have in my manifest file

{
    "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
    }
  }
   
1

There are 1 best solutions below

1
magicwood789 On

Use Database or LocalStorage. Use the variable let tabId as key, the attribute you want to change the value of, e.g.: clicked.

When the listener detects the first time the tab is complete:

  • if clicked is false, then execute script.
  • click button, then update the value of clicked to true.

After clicking the button, sendMessage to runtime update the clicked to true, the tab should then reload or refresh.

The listener detects it again, then clicked is true.

You can type your code in this:

( if(clicked === true))

The Code:

/**
 * 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 should reload or refresh.
                else {
                    handlePrintConsole({
                        from: `tabNew cbOnUpdated`,
                        info: `clicked === true`,
                    })

                    // TODO: Detect the tab is reloading or refreshing!
                    // 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);
    }
}