Alternative to Content script without host_permissions

132 views
Skip to first unread message

Yacine Benslimane

unread,
May 23, 2024, 12:46:29 AMMay 23
to Chromium Extensions
Hello everyone,

I have an extension published on the CWS. In the next update I'm adding a content script, and unfortunately I didn't require host permissions before, which means it'll be disabled for users that have already installed it.

I tried using `scripting.executeScript` each time a tab is loaded:

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (tab.url?.startsWith('chrome://')) return;
    if (changeInfo.status === 'complete') {
        chrome.scripting.executeScript({
            target: { tabId },
            files: ['my-content.js'],
        });
    }
  });

But I receive this error: "Error: Cannot access contents of the page. Extension manifest must request permission to access the respective host."

Is there a way to use a content script with optional host permissions or something similar that prevents the extension from getting disabled?

woxxom

unread,
May 23, 2024, 1:47:24 AMMay 23
to Chromium Extensions, Yacine Benslimane
The only solution to avoid the extension being disabled on update is to use optional_host_permissions and call chrome.permissions.request in your popup or options or a post-install onboarding page. When the call succeeds you will use chrome.scripting.registerContentScripts. See https://developer.chrome.com/docs/extensions/reference/permissions

As for chrome.tabs.onUpdated, it's an inefficient solution that wakes up the background script each time any tab is navigated, so try avoiding it in general.

Yacine Benslimane

unread,
May 23, 2024, 2:06:05 AMMay 23
to Chromium Extensions, woxxom, Yacine Benslimane
That's really helpful. Thank you!
Reply all
Reply to author
Forward
0 new messages