chrome.tabs.get显然不能在内容脚本中工作,除了通过chrome.extension.sendRequest发送它之外,我不知道如何让背景响应正确的选项卡。
如何让内容脚本将信息发送到后台页面,然后后台页面将信息返回到它所在的选项卡?
发布于 2011-03-27 21:03:12
EDIT:此答案已过时,并使用了已弃用的函数。请使用其他答案。
好吧,让我来解释一下,伙计;)
首先,从您的content-script发送一条消息,如下所示:
内容脚本-发送消息
chrome.extension.sendRequest({ action: "WhatYouWant"});后台页面-接收消息和响应
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
{
if(request.action)
{
// Make what you want
chrome.tabs.getSelected(null, function(tabs) {
chrome.tabs.sendRequest(tabs.id, { action: "response" });
});
}
});ContentScript -添加监听程序
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
if(request.action)
{
alert('The response is : ' + request.action);
}
});发布于 2013-02-21 05:56:49
onMessage提供了一个sendResponse函数,可用于将响应直接发送回发送方。
background.js摘录:
chrome.extension.onMessage.addListener(
function(message, sender, sendResponse) {
if ( message.type == 'getTabId' )
{
sendResponse({ tabId: sender.tab.id });
}
}
);content_scripts.js摘录:
var tabId;
chrome.extension.sendMessage({ type: 'getTabId' }, function(res) {
tabId = res.tabId;
});发布于 2015-10-07 04:14:37
出于对2011年后查看此问题的任何人的礼貌,我提供了一个使用较新的约定和API的答案。这是一个相当流行的问题,目前公认的答案有点过时(但仍然是一个准确的答案),所以对于任何新手来说,这应该会为这个问题提供一个更清晰和更适用的答案。
对于初学者,您可以使用chrome.runtime.sendMessage从内容脚本发送消息。这将在发生运行时事件(即单击浏览器操作)时不加区别地发送消息。它看起来像这样:
content.js
chrome.runtime.sendMessage({ from: 'content', message: 'info to send' });由于您需要与事件页通信(根据较新的约定,与持久背景页相比,事件页是首选)来获取有关活动选项卡的信息(假设您只需要选项卡id),因此实际上可以通过添加运行时事件侦听器并检查sender参数来获取该信息。它看起来像这样:
event.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.from == 'content') {
// tabId will hold the sender tab's id value
var tabId = sender.tab.id;
sendResponse({ from: 'event', message: 'any info to send back', tabId: tabId });
}});但是,由于我们需要将该信息传递回内容脚本,因此需要返回并向chrome.runtime.sendMessage添加一个回调处理程序。它现在看起来像这样:
content.js
chrome.runtime.sendMessage({ from: 'content', message: 'info to send' }, function(callbackResponse) {
if (callbackResponse.from == 'event') {
// do what you need to do in here
console.log(callbackResponse.tabId);
}
});此设置现在允许您将简单的一次性消息从content.js传递到event.js,由event.js将信息返回给content.js。
同样,对于那些想要了解新方法如何工作的人来说,这只是一个被接受的答案的更新版本。
https://stackoverflow.com/questions/5448246
复制相似问题