我正在制作Chrome扩展程序,其中包含搜索结果中的说明文字并将其存储在Chrome存储空间中。我使用POST
更改chrome.storage.local.set
中chrome存储空间中的值。然后,我在background-js
中访问它。我删除content.js
时我的扩展程序正在运行,但我希望它只在Chrome存储中的值发生更改时触发。
content.js
onChanged.addListener()
背景-JS
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
if (request.message=="browserAction"){
var link = $('h3.r')
link.click(function(){
var d = this.nextSibling
var description = $(d).find('span.st').text()
var index = description.lastIndexOf("-")
if (index>=0){
var description = description.slice(index+2,description.length-1)
}
alert(description)
chrome.runtime.sendMessage({"message":"linkClicked","description":description})
})
}
})
chrome.storage.onChanged.addListener(function(changes,areaName){
chrome.storage.local.get("keyName",function(items) {//initialize the application
console.log(items.keyName)
var p = document.getElementsByTagName('p')
for (n=0;n<p.length;n++){
console.log(p[n].textContent)
if (p[n].textContent.includes(items.keyName)){
console.log('found a match at paragraph' + p[n])
var newStr = p[n].textContent.replace(items.keyName,"<span style='background-color:yellow'>" + items.keyName + "</span>")
p[n].innerHTML=newStr
$('html, body').animate({
scrollTop: $('p:eq('+n+')').offset().top + 'px'
}, 'fast')
return
}
else{console.log('no match found')}
}
})
})
的manifest.json
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id,{"message":"browserAction"})
});
})
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){ //Listener Not Firing
if (request.message=="linkClicked"){
var d = request.description
console.log(d)
if (d.indexOf('.')>=0){ //this will always evaluate to true and execute, leaving empty string ||||
var d = d.slice(0,d.indexOf('.')) //get a snippet of text
}
}
console.log(d)
chrome.storage.local.set({"keyName": d},function(){console.log('mah critics stored')});
})
答案 0 :(得分:0)
结果是onChanged侦听器WAS触发。新页面打开得太快,我无法在带有链接的页面中的控制台中看到该消息。为了使content.js代码在新打开的选项卡上运行,我使用setTimeout
直到加载新页面。
background.js
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id,{"message":"browserAction"})
});
})
chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
if (request.message=="linkClicked"){
var d = request.description
console.log(d)
if (d.indexOf('.')>=0){ //this will always evaluate to true and execute, leaving empty string ||||
var d = d.slice(0,d.indexOf('.')) //get a snippet of text
}
}
setTimeout(function(){chrome.storage.local.set({"keyName": d});},2000)//Delay
})