跟进一个上一篇文章 https://stackoverflow.com/questions/58951909/programmatic-method-to-let-the-user-modify-the-manifest-json-content-of-a-chrome,我现在正在尝试创建一个未指定的 Chrome 扩展版本content_scripts:
or matches:
in the manifest.json
文件;相反,内容脚本是通过从选项页面触发的 en 事件以编程方式注入的,该事件提示用户授予执行内容脚本的可选权限。其基本原理是能够让扩展程序在具有不同顶级域名的主机的页面上运行(有关详细信息,请参阅上一篇文章)。我已阅读文档 https://developer.chrome.com/extensions/content_scripts#functionality并试图将这些点联系起来,但我还没有完全做到这一点。
下面是我迄今为止创建的演示版本。我设法处理可选权限请求,并显示用户提示授予该请求(显示警报“已授予!”)。但是,当我尝试让消息侦听器进入background.js
执行脚本content.js
(通过删除 /* 注释掉的代码 */ ),我收到错误消息
未选中的runtime.lastError:无法访问url的内容
“chrome-extension://[blah]/options.html”。扩展清单必须
请求访问该主机的权限。
关于我在这里错过的任何指导将是非常受欢迎的。
我还有第二个问题:因为我在中使用 jQuerycontent.js
脚本,我必须执行jQuery.js
文件也响应授予的权限,如果是这样,是否应该通过添加另一个单独的文件来完成chrome.tabs.executeScript()
命令?
清单.json:
{
"manifest_version": 2,
"name": "My Extension",
"version": "1",
"description": "Demo extension",
"options_page":"options.html",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"optional_permissions":["tabs","https://*/*"],
"permissions": ["activeTab","storage"]
}
选项.html:
<html>
<head>
<style>
button#permreq{font-size:2em;}
</style>
</head>
<body>
<button id="permreq">Click this button to enable My Extension</button>
<script src="jQuery.js"></script>
<script src="options.js"></script>
</body>
</html>
选项.js:
jQuery(function($){
$(document).ready(function(){
$("button#permreq").click(function(){
chrome.permissions.request({
permissions: ['tabs'],
origins: ["https://*/*"]
}, function(granted) {
if (granted) {
chrome.runtime.sendMessage("granted");
} else {
alert("denied");
}
});
});
});
});
背景.js:
chrome.runtime.onMessage.addListener(
function(message, callback) {
if (message == "granted"){
/*chrome.tabs.executeScript({
file: "content.js"
});*/
alert("granted!");//no errors as long as above code is commented out
} else{
alert("denied");
}
});