alib_15
alib_15

Reputation: 286

Chrome extension reload

I'm trying to create my first Chrome extension and I've noticed something. I think the problem may lie with the event page.

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {xbank: "click"})
});
});

Everything works fine except when I reload the extension, the above action creates this error "extensions::uncaught_exception_handler:8 Error in response to tabs.query: TypeError: Cannot read property 'id' of undefined".

If I restart Chrome, everything works fine again.

What approach should I take to avoid this possible error?

Edit - thanks to François F for pointing me in the right direction. For anyone learning the ropes, new tabs in Chrome have an invisible chrome://newtab/ URL. Similarly, the extensions page has a chrome://extensions/ URL. And my content script would not execute on either.

chrome.browserAction.onClicked.addListener(function(tab) {
    if((tab.url).toString().indexOf("http")==-1){
        alert("URL for this page is:\n" + tab.url + "\n\nCannot open app on this URL must be http/htttps");
}
else{
        chrome.tabs.sendMessage(tab.id, { xbank: "click" })
    }
});

Upvotes: 0

Views: 557

Answers (1)

François F
François F

Reputation: 154

chrome.browserAction.onClicked already gives you the tab from where the icon was clicked, so you only need to do this:

chrome.browserAction.onClicked.addListener(function(tab) {
    if (!tab)
    {
        return; // this makes sure the browser action was triggered from a tab
    }
    chrome.tabs.sendMessage(tab.id, {
        xbank: "click"
    })
});

Upvotes: 2

Related Questions