Ballon Ura
Ballon Ura

Reputation: 922

Chrome extension inject script only if tab has permission

I am trying to inject content script via chrome.tabs.executeScript command, but it try to inject to every opened tab on the browser. There is a way to deremine if the extension have the right permission for the tab (in the manifest.json, permissions key) before trying to inject script? My error is: Unchecked runtime.lastError: Cannot access contents of url "https://exmaple.com/". Extension manifest must request permission to access this host.

My code is:

 const chromeManifest = chrome.runtime.getManifest();
 chrome.tabs.query({}, tabs => {
    const [script] = chromeManifest?.content_scripts?.[0].js;

    tabs.forEach(tab => {
      /* HERE CHECK IF THERE IS PERMISSION FOR THE TAB */
      chrome.tabs.executeScript(tab.id, {
        file: script,
      });
    });
  });

Upvotes: 3

Views: 642

Answers (1)

woxxom
woxxom

Reputation: 73576

Simply read chrome.runtime.lastError in the callback of executeScript to suppress the error.

chrome.tabs.executeScript(tab.id, { file }, () => chrome.runtime.lastError);

As an optimization in case manifest.json's content_scripts has matches for a specific site pattern, query only the tabs that match this pattern.

Note that <all_urls> pattern will also match chrome://, file://, chrome-extension:// tabs, whereas *://*/* will match only http:// and https://.

chrome.runtime.getManifest().content_scripts.forEach(script => {
  const params = {
    runAt: script.run_at,
    allFrames: script.all_frames,
    matchAboutBlank: script.match_about_blank,
  };
  // <all_urls> is not supported here so we use an empty array
  const urlQuery = script.matches.filter(m => m !== '<all_urls>');
  chrome.tabs.query({ url: urlQuery }, tab => {
    script.js.forEach(file => {
      chrome.tabs.executeScript(tab.id, { ...params, file }, () => {
        const err = chrome.runtime.lastError;
        // if (err) console.warn(err.message); 
      });
    });
  });
});

Upvotes: 1

Related Questions