Morgan
Morgan

Reputation: 63

chrome.tabs.onUpdated listener with script execution works strangely after first load

I'm writing a chrome extension to remove elements from a specific page after it loads and I am seeing inconsistent behavior.

I have two listeners, one is listening for hotkeys and the other is the chrome.tabs.onUpdated listener. Both make an executeScript call to the same additional file.

OnUpdated fails with a manifest permission error at first, and continues to fail on each reload. When I execute the call from the hot key it works, and then the onUpdated call works with subsequent reloads

If I open the page in a new tab, it is back to failing until I execute the call with the hotkey. It also goes back to failing if I reload the extension from the management page.

Am I missing something obvious? I have tried adding http://*/* to my permissions but the behavior is the same.

backgroud.js

chrome.commands.onCommand.addListener(function (command) {
  if (command === "test-alert") {
    try {
      chrome.tabs.executeScript(null, {file: "testalert.js"});
      } catch(err) {
          chrome.extension.getBackgroundPage().console.log(err);
      }   
  }
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
  if(changeInfo.status === "complete" && tab.url.includes("nytimes")){
    chrome.tabs.executeScript(tabId, {file: "testalert.js"});
  };
});

manifest.json

"commands": {
  "test-alert": {
    "suggested_key": {
      "default": "Ctrl+M",
      "mac": "Command+M"
    },
    "description": "test alert"
  }
}

testalert.js

alert("test");

Error:

Unchecked runtime.lastError: Cannot access contents of url "https://www.nytimes.com". Extension manifest must request permission to access this host.

Upvotes: 0

Views: 594

Answers (1)

Marco Bonelli
Marco Bonelli

Reputation: 69336

Am I missing something obvious?

Looks like so. Look at the error message more closely:

Cannot access contents of url "https://www.nytimes.com"

The protocol is https, not http. You should use https://*/* in your manifest "permissions", or maybe even <all_urls> to match all protocols.

Upvotes: 1

Related Questions