首页 > 解决方案 > Chrome 扩展:将脚本注入新创建的 Windows

问题描述

我目前正在尝试构建一个 chrome 扩展,其中一部分使用以下方法创建一个新的“弹出”窗口:

chrome.windows.create({
            url: chrome.runtime.getURL("myHTML.html"),
            type: "popup"
        }, function (window) {
            // Trace tab id which is created with this query 
            myTabID = window.tabs[0].id;
            });

它从我的 html 文件加载一个新窗口并存储所创建窗口的选项卡 ID。

但是我想要做的是将 Jquery 和“myScript.js”注入到“myHTML.html”中,一旦它通过以下方式创建:

//Listen for vocab list window creation
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    // Inject script into chosen tab after it is loaded completely
    if (tabId == myTabID && changeInfo.status == "complete") {
        // Inject jQuery in current tab
        chrome.tabs.executeScript(tabId, {
            "file": "jquery-3.2.1.min.js"
        }, function () {
            console.log("Injected jquery into page");
        });
        // Inject script in current tab
        chrome.tabs.executeScript(tabId, {
            "file": "myScript.js"
        }, function () {
            console.log("Injected myScript into page");
        });
    }
});

但是当我尝试这个时,它给了我一个错误说明:

Unchecked runtime.lastError while running tabs.executeScript:
Cannot access contents of url "chrome-extension://<my extension id>
/myHTML.html". Extension manifest must request permission
to access this host.

我当前的 manifest.json 权限如下:

"permissions": [
    "activeTab",
    "storage",
    "tabs",
    "<all_urls>"
  ]

我试过寻找答案,但似乎找不到任何真正解决我问题的答案。任何帮助,将不胜感激!

标签: javascriptgoogle-chrome-extensionpermissions

解决方案


推荐阅读