4

所以这个想法是这样的......我要做的就是在加载特定内容脚本后立即调用扩展背景页面。(在这种情况下,当加载页面时)我的内容脚本中有类似的内容。

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 时它实际上并没有传递图像

4

1 回答 1

3

问题是您试图在后台页面中实现同步和异步事件之间的同步

a) chrome.tabs.captureVisibleTab()是异步的

b) port.postMessage()是同步的

port.postMessage({response: takeScreenshot() });被调用时,它不会等待takeScreenshot() 回调,即;return img;所以一个空的 JSON 对象被发送到内容脚本

回拨返回后通过发布消息来避免它

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);
        });
    }
    });
});

工作版演示

清单.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"]
    }
  ]
}

背景.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(内容脚本)

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);
});

如果您需要更多信息,请与我们联系。

于 2012-12-04T03:18:05.837 回答