如何解决Chrome 扩展程序只能在新标签页中正常运行
我刚刚启动了 Chrome 扩展程序。我有这个简单的文件结构
清单文件看起来像这样
{ "manifest_version": 2,"name": "fu","description": "block audio from videos set to autoplay","version": "1","author": "ddpf","browser_action": { "default_title": "Have a better day" },"chrome_url_overrides" : { "newtab": "newtab.html"},"permissions": ["activeTab"]}
到目前为止,newtab 是非常基本的,只是 hello world 并链接到 js 文件
<!doctype html>
<html>
<head>
<title>Test</title>
</head> <body>
<h1>Hello World!</h1>
<video>
<iframe width="420" height="345" src="https://www.youtube.com/embed/tgbNymZ7vqY">
</iframe>
</video>
<script src="popup.js"></script>
</body></html>
以及相当基本的 JS 代码
var videos = document.querySelectorAll('video'); /*LooP*/
if (videos.length <= 1) {
console.log("there have been no video elements to mute or remove")
}
else {
var i;
for (i = 0; i < videos.length; i++) {
videos[i].style.display = 'none';
console.log("there have been " + i +" video elements")
}
}
var totalNoOfResrouces = window.performance.getEntriesByType("resource").length;
console.log("totalNoOfResrouces ")
if (totalNoOfResrouces.length <= 10) {
console.log("well done")
}
其他{
console.log("Too many telemetry and tracking and 3rd party,we will redirect this")
}
如果我在新选项卡中运行它,我会得到一个“hello world”渲染,视频和 iframe 在 DOM 中(设置为 display:none,根据需要),我在控制台中得到它。
>there have been 0 video elements (this should show 1 instead of 0,why 0?)
popup.js:19 0 (this seems ok but js line 26 should return the if clause condition on line 22,not the line 26 else clause )
popup.js:26 Too many telemetry and tracking and 3rd party scripts,we will redirect this /// This should show well done,
然而,真正的问题是,如果我更改 URL 或转到任何选项卡并更改 URL,JS 或扩展程序不会在新标签页上运行。
为了测试,我去了 https://www.dailymail.co.uk/news/article-9106063/Biggest-teaching-union-calls-emergency-meeting.html ,邮件中有大量的自动播放视频,瞧,它们都自动播放,控制台中没有任何内容。
在上面的链接上,他们有一个视频元素 #vjs_video_2122_html5_api 在向下滚动时弹出,另一个视频元素具有 html 属性 data-mol-fe-video-preview。两者都运行,看起来他们为视频元素上的广告调用了许多外部服务,控制台中有许多错误,但我的扩展程序中没有任何错误,视频仍然运行。
我还没有为 google 支付 5 美元的开发费,如果它现在只在我的本地机器上运行还可以,这离可发布和业余爱好项目还有很远的距离。但是为什么这只能在新标签页中运行?
我是否必须授予 manifest.json 文件中所有选项卡的权限?我该怎么做?谢谢
解决方法
您希望将 popup.js
注入到您访问的每个页面中,对吗?
在这种情况下,只需将以下代码粘贴到您的 manifest.js
文件中。如果您想查看 console.log 条目,只需打开任何标签页,打开 devtools,console.log 条目就会在那里。
内容脚本被注入到匹配数组中的模式的每个页面中。在下面的代码的情况下,这将是“all-urls”。
另一件事,如果你想给扩展程序访问所有标签的权限,只需删除“activeTab”并将其替换为"<all_urls>"
{
"manifest_version": 2,"name": "fu","description": "block audio from videos set to autoplay","version": "1","author": "ddpf","browser_action": {
"default_title": "Have a better day"
},"chrome_url_overrides": {
"newtab": "newtab.html"
},"content_scripts": [{
"js": ["popup.js"],"matches": [
"<all_urls>"
]
}],"permissions": ["activeTab"]
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。