“无法访问 url 的内容”-Manifest v3 Chrome 扩展

问题描述 投票:0回答:1

我在background.js中遇到错误

Unchecked runtime.lastError: Cannot access contents of url. Extension manifest must request permission to access this host.
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

在 google chrome 清单 3 中。

来自内容脚本的监听器

chrome.runtime.onMessage.addListener(
function(req, sender, sendResponse) {
    if(req.msg === "analysis background") {
        let obj = parse();
        sendResponse(obj);
    }
        
    return true;
}
); 
); 

来自manifest.json的部分代码

{
    "manifest_version": 3,
    "name": "extensionParser",
    "version": "1.0.0",
    "action": { 
        "default_popup": "popups/popup.html"
      },
    "background": {
        "service_worker": "background.js"
    },
    "permissions": ["tabs", "scripting",
        "http://localhost/site_for_parsing"]
}

background.js 文件中的部分代码

const siteUrl = "http://localhost/site_for_parsing";

chrome.runtime.onConnect.addListener(port => {
    port.onMessage.addListener(msg => {
        if(msg.message === 'analysis') {
            chrome.tabs.create({active: false, url: siteUrl}, tab => {
                chrome.scripting.executeScript({
                    target: {tabId:tab.id},
                    files: ['dist/parser.js']
                }, (results) => {
                    chrome.tabs.sendMessage(tab.id, {msg: "analysis background"}, res => {
                        port.postMessage(res)
                        chrome.tabs.remove(tab.id)
                    })
                })
            });
        }

    });
});

我正在等待您的回复

javascript google-chrome-extension manifest.json
1个回答
17
投票
  1. 站点权限应添加到
    host_permissions
    ,而不是
    permissions
    更多信息
  2. ManifestV3 中的
  3. create +executeScript 在 Chrome 100 之前的版本中存在 bug,因此要么 a) 返回 ManifestV2,直到 Chrome 100 稳定,要么 b) 使用下面的解决方法。

等待URL设置完毕:

(async () => {
  const tab = await chrome.tabs.create({url: 'https://www.example.com'});
  const tabId = tab.id;
  if (!tab.url) await onTabUrlUpdated(tabId);
  const results = await chrome.scripting.executeScript({
    target: {tabId},
    files: ['content.js'],
  });
  chrome.tabs.sendMessage(tabId, {msg: 'analysis background'}, res => {
    port.postMessage(res);
    chrome.tabs.remove(tabId);
  });
})();

function onTabUrlUpdated(tabId) {
  return new Promise((resolve, reject) => {
    const onUpdated = (id, info) => id === tabId && info.url && done(true);
    const onRemoved = id => id === tabId && done(false);
    chrome.tabs.onUpdated.addListener(onUpdated);
    chrome.tabs.onRemoved.addListener(onRemoved);
    function done(ok) {
      chrome.tabs.onUpdated.removeListener(onUpdated);
      chrome.tabs.onRemoved.removeListener(onRemoved);
      (ok ? resolve : reject)();
    }
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.