首页 > 解决方案 > 如何在 chrome 扩展 v3 中加载内容脚本

问题描述

我正在将我的 v2 扩展迁移到 v3。现在,我不清楚的第一件事是内容脚本是如何加载到页面中的。我已按如下方式实现它(后台脚本):

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'],
                }, () => {  });
            }
        });
    });
});

我认为这个例子是我最好的尝试:) 所以,当我运行这段代码时,我在控制台中收到以下错误:

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

这是我的清单:

{
    "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
        }
    ]
}

如果我在这里走的是正确的道路,那么我的清单中肯定缺少一些东西。有什么建议么?

标签: javascriptgoogle-chrome-extension

解决方案


尝试以下方法:-

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;
}

推荐阅读