如何将屏幕截图从扩展程序移动到内容脚本?

时间:2012-12-03 23:56:41

标签: javascript google-chrome-extension screen-capture

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

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

1 个答案:

答案 0 :(得分:3)

问题是您正试图在background page

中实现同步和异步事件之间的同步

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

b)port.postMessage()是同步的

port.postMessage({response: takeScreenshot() });被调用时,它不会等待 takeScreenshot() call back,即; return img;因此将空JSON对象发送到content script

posting message返回

之后使用call back避免使用它
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);
});

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