我正在开发一个 chrome 扩展,这里是主要文件:
background.js
getPageDimension = function (){
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, { message: "DIMENSION" }, function(response){
if (response != null) {
console.log(response.x);
console.log(response.y);
console.log(response.w);
console.log(response.h);
}else{
console.log('Response is null');
}
});
});
};
content.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.message && (msg.message == "DIMENSION")) {
var dimension = getPageDiemension(document.documentElement);
console.log(dimension.x);
console.log(dimension.y);
console.log(dimension.w);
console.log(dimension.h);
sendResponse({x: dimension.x, y: dimension.y,w: dimension.w,h: dimension.h});
}
});
getPageDiemension = function(currentDom){
var dimension = new Object();
dimension.x = 0;
dimension.y = 0;
dimension.w = currentDom.scrollWidth;
dimension.h = currentDom.scrollHeight;
return dimension;
}
所以我的目标是获取当前事件选项卡中加载的页面的完整高度和宽度。当我调试我的内容脚本时,我在我的background.js 中得到了正确的响应,但是如果在没有调试的情况下运行脚本,我得到一个undefined
在我的 background.js
中响应。
这是我的 manifest.json
文件中的 cotent.js
声明:
"content_scripts": [{
"all_frames": true,
"matches": [
"http://*/*", "https://*/*"
],
"js": ["content.js"]
}],
请帮助我,我哪里错了?。如果您需要任何进一步的数据,请告诉我。
最佳答案
问题
我在一段时间后发现了您的代码中的两个小问题,因为它看起来工作正常(实际上根本不工作)。
- 您正在使用已弃用的
chrome.tabs.getSelected(...)
方法,您应该避免使用该方法。请改用chrome.tabs.query({active: true, highlighted: true}, ...)
。 在您的
chrome.runtime.onMessage
监听器中,在内容脚本中,您在发送响应之前进行一些计算:这会使消息 channel 在您发送响应之前关闭,并将导致null
响应。引自the official documentation :
This function (
sendResponse
) becomes invalid when the event listener returns, unless you returntrue
from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end untilsendResponse
is called).
解决方案
现在您知道问题出在哪里了,您可以轻松地将旧的 tabs.getSelected()
替换为 tabs.query()
,并添加一个 return true;
内容脚本中 runtime.onMessage
事件处理程序中的语句。解决方案如下,我也轻化了代码。
你的background.js
:
getPageDimension = function (){
chrome.tabs.query({active: true, highlighted: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { message: "DIMENSION" }, function(response){
if (response !== null) console.log('Response:', response);
else console.log('Response is null');
});
});
};
你的content.js
:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.message && (msg.message == "DIMENSION")) {
var dimension = getPageDiemension(document.documentElement);
console.log('Dimension:', dimension);
sendResponse(dimension);
}
return true;
});
getPageDiemension = function(currentDom){
return { x: 0, y: 0,
w: currentDom.scrollWidth,
h: currentDom.scrollHeight
}
}
工作示例
你可以找到我为测试做的工作示例 HERE .
文档链接
为了清楚起见,我给你留下了一些关于这个扩展中涉及的 API 的文档链接,你可能会觉得有用:
关于javascript - 在内容和背景之间传递的 Chrome 扩展消息不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27823740/