我正在处理一些代码,它从浏览器弹出窗口的文本框中获取输入,然后将该输入传递给background.js以便使用该输入来过滤网页。
如果我在background.js中一开始硬编码过滤,则可以工作(因为background.js在启动时运行),但是如果我将过滤放在一个函数内,该函数从popup.js接收输入,则无法正常工作。
popup.js
$(document).ready(function(){
$('#zim').click(function(){
// Get User Input in Text Box
var author = document.getElementById('author').value;
// Pass author variable to background.js
chrome.extension.getBackgroundPage().StartFiltering(author);
});
});
background.js
function StartFiltering(person){
console.log("Starting Filtering");
console.log("person: " +person);
$( "a:contains('" + person + "')" ).closest('.post-wrapper.js_post-wrapper.wide.postlist-dense').remove();
$( ".text-upper:contains('" + person + "')" ).closest('.post-wrapper.js_post-wrapper.wide.postlist-dense').remove();
$( "a:contains('" + person + "')" ).closest('.post-wrapper.js_post-wrapper.postlist-dense').remove();
};
清单文件
{
"name": "Filter",
"description": "Filter out authors on homepage",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["jquery.js","background.js"],
"persistent": false
},
"icons": {
"128": "128.png"
},
"browser_action": {
"default_title": "Filter",
"default_icon": "filter.png",
"default_popup": "popup.html"
},
"manifest_version": 2,
"content_scripts": [
{
"js": ["jquery.js","background.js"],
"matches": [ "http://example.com/*"]
}
]
}
如果我在background.js中将三行jQuery代码放在函数外面,并且硬编码“person”变量并重新加载扩展程序,那么它将正确过滤网站。 StartFiltering函数肯定会运行,肯定能够从用户得到“author”输入,但我认为因为background.js仅在启动时运行,所以它不知道要更新文件?我不确定!对JS和编程还很新!
我在这里搜索过,但找不到有相同问题的人!非常感谢您提供任何帮助!
编辑 - 已解决!
以下是我的解决方法...
在ExpertSystem指出我两次使用了background.js之后,我清理了清单和文件系统,使我有4个文件:background.js、content.js、popup.js和清单。在清单的content_scripts部分,我使用jquery.js和content.js而不是之前的background.js。
当用户在弹出窗口文本框中输入值时,我让popup.js向background.js发送一条消息,这个过程非常简单:
popup.js
chrome.runtime.sendMessage({type: "new author", author:author});
我让background.js监听消息,如果收到的消息类型与popup.js发送的一致,则将阻止作者的值存储在数组中(因为最终我计划保留一个过滤作者列表),并将该数组作为消息发送:
background.js
chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse) {
if(request.type == "new author") {
blocked.push(request.author)
}
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,{filter:"author",blocked:blocked})
});
});
然后我让content.js监听消息:
内容.js
chrome.runtime.onMessage.addListener(function(msg,sender){
if (msg.filter == "author"){
for (var i=0;i<msg.blocked.length;i++){
startFiltering(msg.blocked[i]);
}
}
});
还需要微调,但现在我已经让所有三个页面进行了通信!