我正在研究一些代码,它在浏览器弹出窗口中接受来自文本框的输入,然后将该输入转发到background.js以便过滤使用该输入的网页。使用popup.js中的信息刷新background.js - Google Chrome扩展程序
如果我在开始时对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在函数外部的3行jQuery,以及“人”变量中的硬代码并重新加载扩展,然后它将正确地过滤网站。 StartFiltering肯定会运行,它肯定会得到来自用户的“作者”输入,但我认为,因为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收听的消息:
content.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]);
}
}
});
仍然需要调整,但我都3网页正在通信!
请发布您的清单内容。 – gkalpak
编辑原始帖子与清单!谢谢! –
你想更新哪个页面?背景页面? – gkalpak