【问题标题】:google chrome extension messaging background to context谷歌浏览器扩展消息背景到上下文
【发布时间】:2011-06-19 09:14:47
【问题描述】:

我正在为 Google Chrome 编写扩展程序。内容脚本永远不会看到已从后台页面发送 sendNextProfile 请求。至少,消息 RECEIVED REQUEST FOR NEXT PROFILE 永远不会出现在控制台日志中,并且后台没有看到任何新请求。

这是内容脚本中的代码

//send request for first profile
var currentProfile=0;
chrome.extension.sendRequest({cmd: "openProfile", url: profileLinks[currentProfile]});

//listen for request to send next profile
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.cmd == "sendNextProfile") {
        console.log("RECEIVED REQUEST FOR NEXT PROFILE");
        ++currentProfile;
        chrome.extension.sendRequest({cmd: "openProfile", url: profileLinks[currentProfile]});
    }
});

这是后台页面的代码

//detect when message tab is closed and request new profile
//var closedTabId=null;
chrome.tabs.onRemoved.addListener(function(tabid, removeInfo) { 
    console.log("TAB CLOSED "+tabid);
    if (tabid==msgTabId) {
        chrome.extension.sendRequest({cmd: "sendNextProfile"});
        console.log("REQUESTED NEW PROFILE");
    }   
});

在后台,控制台消息按预期显示,因此看起来请求已发送。那么这段代码是怎么回事?

【问题讨论】:

  • On the background side, the console message appear as expected. 究竟出现了什么消息?标签已关闭或请求新的配置文件或两者兼而有之?

标签: google-chrome-extension messaging


【解决方案1】:

代替:

chrome.extension.sendRequest({cmd: "sendNextProfile"});

应该是:

chrome.tabs.sendRequest(tabId, {cmd: "sendNextProfile"});

但是,如果您的标签被删除,则向该标签发送请求是没有意义的,因为它已经不存在了。也许您需要将其发送到其他选项卡?

【讨论】:

  • 实际上搜索页面应该仍然打开。但是后台没有打开它所以后台还没有学习到搜索页面的tabid。这里的误解是消息被定向到选项卡而不是广播以供任何选项卡听到。但考虑到这一点,更好的方法是将整个搜索结果数组发送到后台并让后台控制处理,因为搜索页面不需要做任何事情,只需将链接收集到一个数组中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
  • 2015-04-17
  • 2014-07-24
相关资源
最近更新 更多