弹出窗口关闭时继续进行 – chrome扩展

我创建了一个Chrome扩展程序,用于搜索给定的单词,然后重复搜索,解除之前找到的单词(弹出窗口打开)。 它运行良好,但现在我想更进一步,使它继续搜索弹出窗口关闭,所以我将代码转移到后台JS文件,但它不会再循环或继续弹出窗口后关闭。

app.html

...     

Search Keyword/Terms

app.js

 function search(that) { var inputText = new String (t1.value); var bkg = chrome.extension.getBackgroundPage(); chrome.tabs.executeScript(null, {code:"$(document.body).highlight('"+inputText+"','"+ bkg.random_color()+"')"}); var searchButton = document.getElementById('search_btn'); searchButton.style.visibility='hidden'; var clearButton = document.getElementById('clear_btn'); clearButton.style.visibility='visible'; bkg.search_repeat(inputText); } document.addEventListener('DOMContentLoaded', function () { var bkg = chrome.extension.getBackgroundPage(); var searchButton = document.getElementById('search_btn'); searchButton.addEventListener('click', search); var clearButton = document.getElementById('clear_btn'); clearButton.addEventListener('click', hl_clear); clearButton.style.visibility='hidden'; var searchQuery = document.getElementById('t1'); searchQuery.addEventListener('keypress', handle_keypress); var delimField = document.getElementById('delim'); delimField.addEventListener('keypress', handle_keypress); }); 

background.js

 function search(that) { var inputText = new String (t1.value); chrome.tabs.executeScript(null, {code:"$(document.body).highlight('"+inputText+"','"+ random_color()+"')"}); var searchButton = document.getElementById('search_btn'); searchButton.style.visibility='hidden'; var clearButton = document.getElementById('clear_btn'); clearButton.style.visibility='visible'; setInterval(function(){ async_search(inputText); }, 2000); } function search_repeat(keyword) { setInterval(function(){ reSearch(inputText); }, 2000); } function reSearch(keyword) { chrome.tabs.executeScript(null, {code:"$(document.body).highlight('"+keyword+"','"+random_color()+"')"}); } 

当你使用getBackgroundPage你调用后台页面DOM并操纵JS,但它在前台弹出窗口中运行。 您希望将消息侦听器添加到后台页面,该页面在后台页面DOM中调用该进程。 onmessage和sendMessage

这将满足您的需求。

编辑

前景:

 function search(that) { var inputText = new String (t1.value); var bkg = chrome.extension.getBackgroundPage(); chrome.tabs.executeScript(null, {code:"$(document.body).highlight('"+inputText+"','"+ bkg.random_color()+"')"}); var searchButton = document.getElementById('search_btn'); searchButton.style.visibility='hidden'; var clearButton = document.getElementById('clear_btn'); clearButton.style.visibility='visible'; chrome.runtime.sendMessage({ search_repeat: inputText //Send method search_repeat with param inputText }); } 

在后台JS:

  chrome.runtime.onMessage.addListener(function(keyword) { //Start the message listener and set an action. Add 'if's here if you want more than 1. setInterval(function(){ reSearch(keyword.search_repeat); }, 2000); });