gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:04:12 24 4
gpt4 key购买 nike

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

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

但我没有运气......我让图像显示在 body 上,但当从 takeScreenshot 返回 img 时它实际上并没有传递图像

最佳答案

问题是您试图在 background page 中实现同步和异步事件之间的同步

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

b) port.postMessage()是同步的

port.postMessage({response: takeScreenshot() }); 被调用时,它不会等待 takeScreenshot() call back IE; 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);
});
}
});
});

工作版本演示

ma​​nifest.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(内容脚本)

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

如果您需要更多信息,请告诉我。

关于javascript - 如何将屏幕截图从扩展程序移动到内容脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13693939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com