所以这个想法是这样的...我想要做的就是在加载特定内容脚本后立即调用扩展背景页面。 (在这种情况下加载页面时)我的内容脚本中有类似的内容。
var port = chrome.extension.connect({name: "screenshot"});
port.postMessage({request: "screenshot"});
port.onMessage.addListener(function(msg) {
var img = document.createElement('img');
img.src = msg.response;
document.body.appendChild(img);
});
在我的background.js页面中有类似的东西
function takeScreenshot(){
chrome.tabs.captureVisibleTab(null, function(img) {
return img;
});
}
chrome.extension.onConnect.addListener(function(port) {
console.assert(port.name == "screenshot");
port.onMessage.addListener(function(msg) {
if (msg.request == "screenshot"){
port.postMessage({response: takeScreenshot() });
}
});
});
但我没有运气......我将图像显示在身体上但是当从takeScreenshot返回img时它实际上没有传递图像
答案 0 :(得分:3)
问题是您正试图在background page
中实现同步和异步事件之间的同步a)chrome.tabs.captureVisibleTab()是异步的
b)port.postMessage()是同步的
当port.postMessage({response: takeScreenshot() });
被调用时,它不会等待 takeScreenshot() call back,即; return img;
因此将空JSON对象发送到content script
chrome.extension.onConnect.addListener(function(port) {
console.assert(port.name == "screenshot");
port.onMessage.addListener(function(msg) {
if (msg.request == "screenshot"){
chrome.tabs.captureVisibleTab(null,{format:"jpeg",quality:100},function(img) {
//post message only after call back return with Data URL
port.postMessage(img);
});
}
});
});
工作版演示
的的manifest.json 强> 的
{
"name":"Screen Shot Demo",
"description":"This demonstrates Screen Shot API",
"manifest_version":2,
"version":"1",
"permissions":["tabs","<all_urls>"],
"background":{
"scripts":["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["myscript.js"]
}
]
}
的 background.js 强> 的
chrome.extension.onConnect.addListener(function(port) {
console.assert(port.name == "screenshot");
port.onMessage.addListener(function(msg) {
if (msg.request == "screenshot"){
chrome.tabs.captureVisibleTab(null,{format:"jpeg",quality:100},function(img) {
//post message only after call back return with Data URL
port.postMessage(img);
});
}
});
});
myscript.js (contentcript)
var port = chrome.extension.connect({
name: "screenshot"
});
port.postMessage({
request: "screenshot"
});
port.onMessage.addListener(function (msg) {
var img = document.createElement('img');
img.src = msg;
document.body.appendChild(img);
});
如果您需要更多信息,请与我们联系。