Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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,
      });
    });
  });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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); 
      });
    });
  });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!