使用chrome.runtime.sendMessage向内容脚本(ContentScript)发送消息无效

参考Chrome插件(Extensions)开发攻略调试Chrome扩展的时候,发现从内容脚本(ContentScript)向后台脚本(BackgroundScript)使用chrome.runtime.sendMessage发送消息的时候,后台脚本(BackgroundScript)可以接收到来自内容脚本(ContentScript)的消息。

但是从后台脚本(BackgroundScript)向内容脚本(ContentScript)发送消息的时候,内容脚本(ContentScript)无法接收到消息。

原来的发送命令函数如下:

function sendMessageToContentUrl(){
	var msg = {
		type: "req"
	};
	// to send back your response  to the current tab
	chrome.runtime.sendMessage(msg, function (response) { });
}

根据Google了解到,需要指定tab发送,主要原因是当多个页面同时加载了内容脚本(ContentScript)的情况下,直接发送消息,会导致无法区分到底是发送给哪个页面的。
正确的发送消息函数如下:

function sendMessageToContentUrl(){
	var msg = {
		type: "req"
	};
	// to send back your response  to the current tab
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
		 chrome.tabs.sendMessage(tabs[0].id, msg, function(response) { });
		 });
}

参考链接


chrome.runtime.sendMessage not working in Chrome Extension

发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注