Kluny
Kluny

Reputation: 189

Chrome extension browser action only works once

When a user clicks the browser icon, spiderSimulator() should run. I can get it to work – once.

Like, I’ll click the icon and it does what it’s supposed to. But if I refresh the page and click it a second time, it doesn’t work. if I go to another site and try again, it doesn’t work.

If I update the extension, refresh the page, and clear the cache, it works again – sometimes. it’s super inconsistent.

Any idea what’s going wrong here?

content.js

// Adds an event listener to the browser icon to sends a message to background.js.
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.message === "clicked_browser_action") {
            console.log( 'send message' );
            chrome.runtime.sendMessage({"message": "spider_simulator"});
        }
    }
);

background.js

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function (tab) {
    // Send a message to the active tab
    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        var activeTab = tabs[0];
        console.log('browser action');
        chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
    });
});

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.message === "spider_simulator") {
            console.log('run the spider');
            spiderSimulator()
        }
    }
);

// removes the site's stylesheet and replaces it with my own; 
// turns all page elements into nested list items. 
function spiderSimulator() {

    console.log( 'inject stylesheet' );
    chrome.tabs.insertCSS({
        file: 'search-spider-simulator.css'
    });

    console.log( 'execute script' );
    chrome.tabs.executeScript({
        file: 'search-spider-simulator.js'
    });

    window.close();
}

Upvotes: 0

Views: 221

Answers (1)

Xan
Xan

Reputation: 77541

As mentioned by wOxxOm, window.close() executed in the background page acts on itself - essentially terminating the background portion of your extension.

Not sure what was meant there; if you need to close the tab you're talking to, then this also needs to be executeScript'ed.

Upvotes: 0

Related Questions