CJ *_*pha 14 javascript google-chrome google-chrome-extension google-chrome-app
一点背景
我已经在Chrome扩展程序上工作了几天,每天多次截取给定网页的屏幕截图.我用它作为指导,事情按预期工作.
但是,有一个小的要求扩展无法满足.用户必须有权访问保存图像(屏幕截图)的文件夹,但Chrome扩展程序无权访问文件系统.另一方面,Chrome应用程序可以.因此,经过多次回顾,我得出结论,我必须创建Chrome扩展程序和Chrome应用程序.我们的想法是扩展会创建一个屏幕截图,然后将该blob发送到应用程序,然后将其作为图像保存到用户指定的位置.而这正是我正在做的事情 - 我正在扩展端创建一个screentshot的blob然后将其发送到应用程序,在那里要求用户选择保存图像的位置.
问题
直到保存部分,一切都按预期工作.blob在扩展程序上创建,发送到应用程序,由应用程序接收,用户被问到保存位置,图像被保存....这就是事情崩溃的地方.生成的图像无法使用.当我尝试打开它时,我收到一条消息"无法确定类型".以下是我正在使用的代码:
首先在EXTENSION方面,我创建一个blob并发送它,像这样:
chrome.runtime.sendMessage(
APP_ID, /* I got this from the app */
{myMessage: blob}, /* Blob created previously; it's correct */
function(response) {
appendLog("response: "+JSON.stringify(response));
}
);
Run Code Online (Sandbox Code Playgroud)然后,在APP方面,我收到blob并试图像这样保存它:
// listen for external messages
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (sender.id in blacklistedIds) {
sendResponse({"result":"sorry, could not process your message"});
return; // don't allow this extension access
} else if (request.incomingBlob) {
appendLog("from "+sender.id+": " + request.incomingBlob);
// attempt to save blob to choosen location
if (_folderEntry == null) {
// get a directory to save in if not yet chosen
openDirectory();
}
saveBlobToFile(request.incomingBlob, "screenshot.png");
/*
// inspect object to try to see what's wrong
var keys = Object.keys(request.incomingBlob);
var keyString = "";
for (var key in keys) {
keyString += " " + key;
}
appendLog("Blob object keys:" + keyString);
*/
sendResponse({"result":"Ok, got your message"});
} else {
sendResponse({"result":"Ops, I don't understand this message"});
}
}
);
Run Code Online (Sandbox Code Playgroud)
这是执行实际保存的APP上的功能:
function saveBlobToFile(blob, fileName) {
appendLog('entering saveBlobToFile function...');
chrome.fileSystem.getWritableEntry(_folderEntry, function(entry) {
entry.getFile(fileName, {create: true}, function(entry) {
entry.createWriter(function(writer) {
//writer.onwrite = function() {
// writer.onwrite = null;
// writer.truncate(writer.position);
//};
appendLog('calling writer.write...');
writer.write(blob);
// Also tried writer.write(new Blob([blob], {type: 'image/png'}));
});
});
});
}
Run Code Online (Sandbox Code Playgroud)没有错误.没有打嗝.代码可以工作,但图像没用.我到底错过了什么?我哪里错了?我们只能在扩展/应用之间传递字符串吗?斑点在路上被破坏了吗?我的应用程序是否无法访问blob,因为它是在扩展程序上创建的?任何人都可以请一些亮点?
更新(9/23/14) 对于最新的更新感到抱歉,但我被分配到另一个项目,直到2天前才回复.
因此,经过多次调查,我决定采用@Danniel Herr的建议,建议使用SharedWorker和嵌入在应用程序框架中的页面.我们的想法是扩展程序将blob提供给SharedWorker,后者将blob转发到嵌入应用程序框架中的扩展中的页面.该页面然后使用parent.postMessage(...)将blob转发到应用程序.这有点麻烦,但它似乎是我唯一的选择.
让我发布一些代码,以便更有意义:
延期:
var worker = new SharedWorker(chrome.runtime.getURL('shared-worker.js'));
worker.port.start();
worker.postMessage('hello from extension'); // Can send blob here too
worker.port.addEventListener("message", function(event) {
$('h1Title').innerHTML = event.data;
});
Run Code Online (Sandbox Code Playgroud)
的proxy.js
var worker = new SharedWorker(chrome.runtime.getURL('shared-worker.js'));
worker.port.start();
worker.port.addEventListener("message",
function(event) {
parent.postMessage(event.data, 'chrome-extension://[extension id]');
}
);
Run Code Online (Sandbox Code Playgroud)
proxy.html
<script src='proxy.js'></script>
Run Code Online (Sandbox Code Playgroud)
共享worker.js
var ports = [];
var count = 0;
onconnect = function(event) {
count++;
var port = event.ports[0];
ports.push(port);
port.start();
/*
On both the extension and the app, I get count = 1 and ports.length = 1
I'm running them side by side. This is so maddening!!!
What am I missing?
*/
var msg = 'Hi, you are connection #' + count + ". ";
msg += " There are " + ports.length + " ports open so far."
port.postMessage(msg);
port.addEventListener("message",
function(event) {
for (var i = 0; i < ports.length; ++i) {
//if (ports[i] != port) {
ports[i].postMessage(event.data);
//}
}
});
};
Run Code Online (Sandbox Code Playgroud)
在应用程序上
context.addEventListener("message",
function(event) {
appendLog("message from proxy: " + event.data);
}
);
Run Code Online (Sandbox Code Playgroud)
所以这是执行流程......在扩展上,我创建了一个共享工作者并向其发送消息.共享工作者应该能够接收blob,但出于测试目的,我只发送一个简单的字符串.
接下来,共享工作程序接收消息并将其转发给已连接的每个人.app中框架内的proxy.html/js确实已经连接,并且应该接收共享工作者转发的任何内容.
接下来,proxy.js [应该]从共享工作者接收消息并使用parent.postMessage(...)将其发送到应用程序.该应用程序正在通过window.addEventListener("message",...)进行侦听.
要测试此流程,我首先打开应用程序,然后单击扩展按钮.我在应用程序上没有收到任何消息.我也没有错.
扩展可以很好地与共享工作者来回通信.该应用程序可以很好地与共享工作人员进行通信.但是,我从扩展名 - >代理 - >应用程序发送的消息未到达该应用程序.我错过了什么?
对于那些长篇大论的人来说很抱歉,但是我希望有人能说清楚,因为这让我疯了.
谢谢
谢谢你们的帮助.我发现解决方案是将blob转换为扩展名上的二进制字符串,然后使用chrome的消息传递API将字符串发送到应用程序.在应用程序上,我接着做了Francois建议将二进制字符串转换回blob的内容.之前我曾尝试过这个解决方案但是我没有工作,因为我在应用程序上使用了以下代码:
blob = new Blob([blobAsBinString], {type: mimeType});
Run Code Online (Sandbox Code Playgroud)
该代码可能适用于文本文件或简单字符串,但它对图像失败(可能是由于字符编码问题).那就是我疯狂的地方.解决方案是使用Francois从一开始就提供的内容:
var bytes = new Uint8Array(blobAsBinString.length);
for (var i=0; i<bytes.length; i++) {
bytes[i] = blobAsBinString.charCodeAt(i);
}
blob = new Blob([bytes], {type: mimeString});
Run Code Online (Sandbox Code Playgroud)
该代码重新训练二进制字符串的完整性,并在应用程序上正确地重新创建blob.
现在我还将我在这里找到的东西和RobW别处的建议结合起来,这就是将blob拆分成块并将其发送出来,以防blob太大.整个解决方案如下:
关于扩展:
function sendBlobToApp() {
// read the blob in chunks/chunks and send it to the app
// Note: I crashed the app using 1 KB chunks. 1 MB chunks work just fine.
// I decided to use 256 KB as that seems neither too big nor too small
var CHUNK_SIZE = 256 * 1024;
var start = 0;
var stop = CHUNK_SIZE;
var remainder = blob.size % CHUNK_SIZE;
var chunks = Math.floor(blob.size / CHUNK_SIZE);
var chunkIndex = 0;
if (remainder != 0) chunks = chunks + 1;
var fr = new FileReader();
fr.onload = function() {
var message = {
blobAsText: fr.result,
mimeString: mimeString,
chunks: chunks
};
// APP_ID was obtained elsewhere
chrome.runtime.sendMessage(APP_ID, message, function(result) {
if (chrome.runtime.lastError) {
// Handle error, e.g. app not installed
// appendLog is defined elsewhere
appendLog("could not send message to app");
}
});
// read the next chunk of bytes
processChunk();
};
fr.onerror = function() { appendLog("An error ocurred while reading file"); };
processChunk();
function processChunk() {
chunkIndex++;
// exit if there are no more chunks
if (chunkIndex > chunks) {
return;
}
if (chunkIndex == chunks && remainder != 0) {
stop = start + remainder;
}
var blobChunk = blob.slice(start, stop);
// prepare for next chunk
start = stop;
stop = stop + CHUNK_SIZE;
// convert chunk as binary string
fr.readAsBinaryString(blobChunk);
}
}
Run Code Online (Sandbox Code Playgroud)
在应用程序上
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (sender.id in blacklistedIds) {
return; // don't allow this extension access
} else if (request.blobAsText) {
//new chunk received
_chunkIndex++;
var bytes = new Uint8Array(request.blobAsText.length);
for (var i=0; i<bytes.length; i++) {
bytes[i] = request.blobAsText.charCodeAt(i);
}
// store blob
_blobs[_chunkIndex-1] = new Blob([bytes], {type: request.mimeString});
if (_chunkIndex == request.chunks) {
// merge all blob chunks
for (j=0; j<_blobs.length; j++) {
var mergedBlob;
if (j>0) {
// append blob
mergedBlob = new Blob([mergedBlob, _blobs[j]], {type: request.mimeString});
}
else {
mergedBlob = new Blob([_blobs[j]], {type: request.mimeString});
}
}
saveBlobToFile(mergedBlob, "myImage.png", request.mimeString);
}
}
}
);
Run Code Online (Sandbox Code Playgroud)
我的应用程序是在扩展程序上创建的,因此无法访问它吗?谁能给我一些启示?
究竟!您可能需要传递a dataUrl而不是blob。下面的内容可能会起作用:
/* Chrome Extension */
var blobToDataURL = function(blob, cb) {
var reader = new FileReader();
reader.onload = function() {
var dataUrl = reader.result;
var base64 = dataUrl.split(',')[1];
cb(base64);
};
reader.readAsDataURL(blob);
};
blobToDataUrl(blob, function(dataUrl) {
chrome.runtime.sendMessage(APP_ID, {databUrl: dataUrl}, function() {});
});
/* Chrome App */
function dataURLtoBlob(dataURL) {
var byteString = atob(dataURL.split(',')[1]),
mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], {type: mimeString});
return blob;
}
chrome.runtime.onMessageExternal.addListener(
function(request) {
var blob = dataURLtoBlob(request.dataUrl);
saveBlobToFile(blob, "screenshot.png");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5289 次 |
| 最近记录: |