发出executeScript权限

Dav*_*sto 2 javascript permissions google-chrome-extension

我正在尝试从后台脚本向选定的选项卡上下文中注入一些代码,但是权限方面存在一些问题。

manifest.json

{
  "manifest_version": 2,
  "name": "prova",
  "version": "1.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": ["https://*"],
      "css": ["mystyles.css"],
      "js": ["myscript.js"]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

background.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    chrome.tabs.executeScript(null,{code:"console.log('Not done!');"});
    sendResponse({});
  });
Run Code Online (Sandbox Code Playgroud)

myscript.js

chrome.runtime.sendMessage({}, function(response) {
    console.log("Done!");
  });
Run Code Online (Sandbox Code Playgroud)

那是错误出现在后台控制台中:

运行tabs.executeScript时未选中的runtime.lastError:无法访问页面的内容。扩展清单必须请求访问相应主机的权限。

我真的很感谢每一个建议。万分感谢。

Del*_*iaz 5

程序化注入部分:

要将代码插入页面,扩展程序必须具有页面的跨域权限。它还必须能够使用chrome.tabs模块。您可以使用清单文件的“权限”字段获得两种权限。

这意味着您需要为要在其中运行代码的主机申请许可。因此,您permissions在中的部分manifest.json应为:

"permissions": [
  "tabs",
  "http://*.example.com/",
]
Run Code Online (Sandbox Code Playgroud)

Take a look at host match patterns.

EDIT 1:

I also noticed that you using a content-script and programmatic injection. These two ways to run code in a tab makes almost the same job but with the different ways.

  1. content_script section from the manifest helps to run a script on every page that matches a host pattern.
  2. programmatic injection (PI) also helps to run a code (file or a string). But host permission for that should be set via section permissions in the manifest. PI uses when a script needs to run rarely, not on every page.