0

I have set something in local storage (where tabId is the id of the triggering tab [onUpdated event])

var visited = {};
visited[tabId] = true;
chrome.storage.local.set(visited);

I then wish to change the stored variable to false when the page unloads (which I gather happens on refresh, moving to a new webpage or closing the tab)

window.onunload = resetStorage;

function resetStorage() {

    var visited = {};

    chrome.tabs.query({ currentWindow: true }, function (result) {
        result.forEach(function (tab) {
            visited[tab.id] = false;
            console.log(visited);
            chrome.storage.local.set(visited);
        });
    });
};

But this doesn't seem to be triggering (I can't get a console.log to come out, not sure if you can on an unload event?) as it does not change the stored values.

What am I doing wrong?

As some background I am keeping track of whether I have already run code on a page so that it doesn't trigger multiple times from iframe loading or redirections (I think I need additional code to handle redirects).

  • 2
    The background page is a separate hidden page, not related in any way to a web page so `window.onunload` refers to the background page DOM and hence is useless. You need to use it in a content script but it won't work anyway because 1) `chrome.tabs.query` isn't available in a content script and 2) the page will be closed before the asynchronous code in unload handler runs (all callbacks in chrome API are invoked asynchronously). You'll have to think of another approach. – wOxxOm Sep 11 '17 at 09:29
  • Please [edit] the question to be on-topic: include a [mcve] that *duplicates the problem*. For Chrome extensions or Firefox WebExtensions you almost always need to include your *manifest.json* and some of the background, content, and/or popup scripts/HTML, and often webpage HTML/scripts. Questions seeking debugging help ("why isn't my code working the way I want?") must include: (1) the desired behavior, (2) a specific problem or error and (3) the shortest code necessary to reproduce it *in the question itself*. Please also see: [What topics can I ask about here?](/help/on-topic), and [ask]. – Makyen Sep 12 '17 at 04:22

0 Answers0