lok*_*gfx 5 google-chrome-extension
介绍
我的Chrome扩展程序出了问题.它应该显示一个小的叠加弹出窗口(在jQuery中创建),其中包含来自Google的搜索结果,基于您的文本选择.基本上你应该可以在任何页面上突出显示文本,右键单击它(上下文菜单),点击"搜索'选择的关键字'",并在同一个标签中弹出一个小窗口作为覆盖图,其中包含所有搜索结果谷歌.
问题
它的工作原理如此,仅仅是第一次.当我突出显示另一个关键字并搜索它时,扩展程序仍会记住以前的关键字并同时抛出2个窗口.如果我要搜索另一个关键字,它会给我3个窗口,其中包含2个先前的搜索和一个新的...
我尝试在执行后删除后台脚本中的监听器,但是没有用.看起来旧的侦听器在那里,他们正在回复来自内容脚本的请求.我可以以某种方式删除它们吗?
我试图把:
chrome.extension.onConnect.removeListener(listener);
Run Code Online (Sandbox Code Playgroud)
在getClickHandler()函数的末尾,但不起作用.
我也在想,也许背景脚本中的这段代码可以做到这一点,但不确定
return function(info, tab) {
Run Code Online (Sandbox Code Playgroud)
拜托,你有什么建议吗?
提前谢谢了!
PS.此弹出窗口目前无法关闭,我知道这一点.但您可以随时刷新页面以获得干净的窗口.问题是我第二次会在同一时间打开2个弹出窗口...等等如上所述.
清单文件:
{
"name": "Easy search Accelerator",
"version": "1.0",
"manifest_version": 2,
"description": "Easily search for anything...",
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"background": {
"scripts": ["sample.js"]
},
"permissions": [
"contextMenus",
"tabs",
"http://*/*",
"https://*/*"
],
"manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)
后台页面/脚本(sample.js):
chrome.contextMenus.create({
"title": 'Search for "%s"',
"contexts":['selection'],
"onclick": getClickHandler()
});
function getClickHandler() {
return function(info, tab) {
var url = "https://www.google.co.uk/search?q=" + info.selectionText;
chrome.extension.onConnect.addListener(function listener(port) {
console.assert(port.name == "searchQuery");
port.onMessage.addListener(function(msg) {
if (msg.keywordRequest == "Yes")
port.postMessage({keyword: url});
});
});
chrome.tabs.executeScript(null, { file: "jquery-1.7.2.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "frame.js" });
});
};
};
Run Code Online (Sandbox Code Playgroud)
内容脚本(frame.js)
var port = chrome.extension.connect({name: "searchQuery"});
port.postMessage({keywordRequest: "Yes"});
port.onMessage.addListener(function listen(msg) {
var test = msg.keyword;
$("body").append("<div style=\"position: fixed;top: 20px;right: 20px;z-index: 9999;\"><iframe style=\"border:1px solid #868686;-webkit-box-shadow: 2px 2px 20px 1px rgba(0, 0, 0, 0.5);\" src=\""+ test +"\" width=328 HEIGHT=240></iframe></div>");
});
Run Code Online (Sandbox Code Playgroud)
端口应该用于长期"连接".
chrome.extension.sendRequest(内容脚本)和chrome.extension.onRequest(背景)应该在你的情况下使用(sendMessage/ onMessage而不是*Request在Chrome 20+中).
这些方法可以使用如下:
onRequest在后台绑定事件sendRequest(request_obj, response_func)response_func.PS.你真的包括jQuery,只是为了追加一个字符串?如果是,我强烈建议删除jQuery并使用vanilla JavaScript:
var div = document.createElement('div');
div.style.cssText = "position: fixed;top: 20px;right: 20px;z-index: 9999;";
div.innerHTML = "<iframe style=\"border:1px solid #868686;-webkit-box-shadow: 2px 2px 20px 1px rgba(0, 0, 0, 0.5);\" src=\""+ test +"\" width=328 HEIGHT=240></iframe>";
document.body.appendChild(div);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2654 次 |
| 最近记录: |