0

使用chrome.tabs.executeScript,如何在插入的内容脚本中使用 background.js 中的变量?我的意思是这样的:

(...)
var identificador = target.selectionText;
chrome.tabs.executeScript(null,
                       {code:"alert(identificador);"});
(...)

这只是我需要做的一个例子。在我的扩展中,我的目标是设置一个变量,其中选择了一部分文本(使用上下文菜单),当重新加载网络时,在文档中搜索它,如果找到匹配项,提醒我。我知道这样做的唯一方法是使用正则表达式和document.body.innerText,但我相信我只能使用document.body.innerText注入 JS 和executeScript. 那么......是否存在更好的方法来做到这一点?如果没有,我如何将带有文本部分的变量发送到由执行的代码executeScript

4

1 回答 1

3

将信息从背景页面 (background.js) 传递到正在查看的网页的最佳方式是结合使用Content ScriptsMessage Passing

内容脚本允许您将 JS 文件添加到网页。这将用于接收来自 background.js 的消息并对网页 DOM 执行操作。

消息传递为您提供了一种通过传递 JSON 对象在后台页面和网页之间进行通信的机制。

添加内容脚本的示例:

{
    "name": "My extension",
    "permissions": [
        "tabs"
    ],
    "content_scripts": [{
        "js": ["myscript.js"]
    }]
}

的示例内容background.js

// Get the current tab and send a message from it:
chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendMessage(tab.id, {
        identificador: target.selectionText
    });
});

的示例内容myscript.js

// Listen to the message
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(request.identificador);      
});

请注意,Google 现在建议您使用Event Pages而不是Background Pages

于 2013-05-11T19:01:54.133 回答