chrome extension - send message from content script to background page and back to content script?

时间:2015-06-25 18:53:49

标签: javascript jquery google-chrome google-chrome-extension

I have no idea if this is the most efficient way of doing what I'm trying to do, if isn't by all means tell me. I'm building a chrome extension that is supposed to loop through each word on the page, and then compare it to a list of 12,000 elements in an array. I managed to make it work on the content script page, but to my dismay, it takes about 7 seconds to load my content script because of all the looping that is taking place. This isn't ideal, obviously. So I had the idea of sending all the p tags to the background page, where it then compares the p words to the array, and once it figures out which match, it sends a message back to the content script with a smaller array of just the words that are located both in the p tags and in my array. Now my question is, is this possible? Will it reduce the load time? Is this efficient? One final question: My manifest is using a background page in the form of html but if I wanted to also use a background script Google doesn't allow that, so can I place my background script in the background page html file and will it load that script?

1 个答案:

答案 0 :(得分:2)

对于您的第一个问题,是的,可以这样做。它将在后台(和隐藏)页面中执行您的重度处理。带有内容脚本的页面不会以这种方式冻结。

你可以这样做:

在后台脚本中:

function heavyStuff(request, sender, sendResponse)
{

    ...
    doSomeThing(request)
    doOtherThing()
    ...

    sendResponse(youreSmallerArray)
}

chrome.runtime.onMessage.addListener(heavyStuff)

在您的内容脚本中:

function manageResponse(smallerArray)
{
    ...
    doWhatYouWant(smallerArray)
    ...
}

arrayOfP = $("p")
chrome.runtime.sendMessage(arrayOfP, manageResponse)

所以它会做你想要的,但你确定你在做什么吗?也许你的算法必须改进?

有关Chrome消息系统的详细信息,请参阅documentation

特别是如果您必须发送大量消息,请查找长期连接部分。

对于第二个问题,您可以在清单中替换背景页面属性:

"background":
{
    "scripts":
    [
        "background.js",
        "otherScript.js",
        ....
        "theLastScript.js"
    ]
}

Chrome会自动创建一个包含此脚本的背景页面(按相同顺序)。

PS:下次您在本网站发帖时,请一次只询问一个问题; - )