Chrome 扩展程序自动触发
我正在制作一个 chrome 扩展来查找我正在使用 browser_action
的页面中的所有链接。当您刷新页面时,我遇到一个错误,chrome 扩展会自动触发 javascript 代码。我该如何做到这一点,以便如果您在浏览器上点击刷新,扩展程序就不会触发?我只希望它在单击工具栏上的小图标时起作用。
这就是我的清单的样子,
{
"name": "Find all first",
"version": "1.0",
"description": "Find all Linkes",
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
},
"icons": {
"16": "icon.png",
"128": "icon-big.png"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [ {
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"]
}]
}
然后我在 popup.html 中调用它
chrome.tabs.executeScript(null, {file: 'content.js'}, function() {
console.log('Success');
});
I am making a chrome extension to find all links in a page I am using a browser_action
. I am getting a bug on when you refresh the page, the chrome extension automatically triggers the javascript code. How would I make it so that if you hit the refresh on the browser the extension doesn't trigger? I only want it to work when the click the little icon on the toolbar.
This is how my manifest looks like
{
"name": "Find all first",
"version": "1.0",
"description": "Find all Linkes",
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
},
"icons": {
"16": "icon.png",
"128": "icon-big.png"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [ {
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"]
}]
}
I am then calling this in my popup.html
chrome.tabs.executeScript(null, {file: 'content.js'}, function() {
console.log('Success');
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您在清单中定义了
contents_scripts
,因此每次加载与您的matches
匹配的页面时,content.js
都会作为内容脚本运行(所以,任何网页都可以)。要仅在用户单击页面操作按钮时在页面上运行
content.js
,请从清单中删除content_scripts
部分,以便不会自动运行任何脚本。然后,当单击“页面操作”按钮时,popup.html 将按其应有的方式执行content.js
。Because you have
contents_scripts
defined in your manifest,content.js
is being run as a content script every time a page is loaded that matches yourmatches
(so, any webpage really).To only run
content.js
on the page when the user clicks your Page Action button, remove thecontent_scripts
section from your manifest, so that no scripts are run automatically. Then, when the Page Action button is clicked, popup.html will executecontent.js
as it should.