谷歌浏览器扩展程序 - 单击图标可调用函数
Google Chrome Extensions - Clicking an icon calls a function
我一直在尝试制作一个带有图标的扩展,单击该图标将停止加载(所有)选项卡。
我有这个清单文件:
{
"name": "Stop Loading",
"version": "1.0",
"manifest_version": 2,
"description": "Stop loading all tabs in Chrome",
"browser_action": {
"default_icon": "greyclose.png"
},
"background_page": "background.html",
"content_scripts": [ {
"all_frames": true,
"js": [ "kliknuto.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"permissions": [ "tabs", "http://*/*", "https://*/*" ]
}
在后台.html我有以下代码:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.extension.sendRequest({reqtype: "get-settings"}, function(response) {
window.setTimeout("window.stop();", 0);
});
});
我不确定我是否应该将背景.html代码放入JavaScript文件"kliknuto.js"或其他东西中。当您在 Chrome 中点击扩展程序按钮时会调用哪个函数?
在你的代码中,background.html 正在向自身发送查询(chrome.extension.sendRequest
不会发送到内容脚本),然后,如果/当它得到回复时,后台页面会调用 window.stop()
自身,而不是选项卡。 您真正需要的是:
背景.html:
...
chrome.browserAction.onClicked.addListener(function(tab) {
// get all tabs in all windows
chrome.windows.getAll({"populate":true}, function(winArray) {
for(var i = 0; i < winArray.length; ++i) {
for(var j = 0; j < winArray[i].tabs.length; ++j) {
var t = winArray[i].tabs[j];
// push code to each tab
chrome.tabs.executeScript(t.id, {"code":"window.stop();", "allFrames":"true"});
}
}
});
});
...
此解决方案使用executeScript
代替内容脚本。
使用替代解决方案进行编辑:
将内容脚本附加到每个选项卡,以侦听来自背景页面的订单。
背景.html:
...
chrome.browserAction.onClicked.addListener(function(tab) {
// get all tabs in all windows
chrome.windows.getAll({"populate":true}, function(winArray) {
for(var i = 0; i < winArray.length; ++i) {
for(var j = 0; j < winArray[i].tabs.length; ++j) {
var t = winArray[i].tabs[j];
// push code to each tab
chrome.tabs.sendRequest(t.id, {"order":"stop"});
}
}
});
});
...
kliknuto.js:
chrome.extension.onRequest(function(request) {
if(request.order == "stop") {
window.stop();
}
});
请确保将"run_at":"document_start"
添加到清单中的content_script
块,以便内容脚本尽快开始侦听。
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量