Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29097

How to load content script in chrome extension v3

I'm migrating my v2 extension to v3. Now, the first thing that is not clear to me is how the content script is loaded into the page. I've implemented it as follows (background script):

chrome.action.onClicked.addListener(tab => {
    chrome.windows.create({
        // Just use the full URL if you need to open an external page
        url: chrome.runtime.getURL("hello.html"),
         type: "panel", height: 200, width:200
    }, (win) => {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            const currTab = tabs[0];
            if (currTab) {
                chrome.scripting.executeScript({
                    target: {tabId: currTab.id},
                    files: ['/content.js'],
                }, () => {  });
            }
        });
    });
});

I think that this example is my best attempt :) So, when I run this code I get the following error in the console:

Unchecked runtime.lastError: Cannot access contents of url "". Extension manifest must request permission to access this host.

Here is my manifest:

{
    "name": "Hello, World!",
    "version": "1.0",
    "manifest_version": 3,
    "background": { "service_worker": "background.js" },
    "action": {
        "default_icon": { 
            "16": "icon16.png"
        }
    },
    "permissions": [
        "tabs",
        "bookmarks",
        "unlimitedStorage",
        "activeTab",
        "scripting"
    ],
    "optional_permissions": [],
    "host_permissions": [
        "*://*/*"
    ],
    "web_accessible_resources": [
        {
            "resources": ["/content.js"],
            "matches": [],
            "extension_ids": [],
            "use_dynamic_url": true
        }
    ]
}

If I'm on the right path here, there must be something missing in my manifest. Any suggestions?

Upvotes: 2

Views: 2934

Answers (1)

Naman Vyas
Naman Vyas

Reputation: 99

try the following :-

chrome.action.onClicked.addListener(insertScript)


async function insertScript() {
    tabId = await getTabId();
    chrome.scripting.executeScript({
        target: {tabId: tabId}
        files: ['/content.js']
    })
}


async function getTabId() {
    var tabs = await chrome.tabs.query({active: true, currentWindow: true});
    return tabs[0].id;
}

Upvotes: 4

Related Questions