After adding the right permissions to the manifest file, you can deal with cross-origin data as without being hindered by the same origin policy. In a background page or any other page within the extension's process, you can get a working demo of your described logic as follows:
// background.js
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var image = document.createElement('img');
image.onload = function() {
context.drawImage(image, 0, 0);
// Demo: Show image
window.open(canvas.toDataURL('image/png'));
};
image.src = 'https://stackoverflow.com/favicon.ico';
Here is a minimal manifest file for this specific demo:
{
"name": "Get image data",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"permissions": [
"https://stackoverflow.com/favicon.ico",
"http://cdn.sstatic.net/stackoverflow/img/favicon.ico"
]
}
The second permission is necessary because https://stackoverflow.com/favicon.ico redirects to http://cdn.sstatic.net/stackoverflow/img/favicon.ico.
Note that the code does not work in content scripts, because the DOM is shared and Chrome cannot offer unrestricted origin access to content scripts only.
Depending on what you really want, you could also just try to get the image data in raw form using XMLHttpRequest
, and process it in any way you desire. This method also works in content scripts, and their advantage is that it is more efficient, and also preserves the bytes of the image (with the canvas method, the image is parsed and processed by the browser before it is converted to a data URL).
var x = new XMLHttpRequest();
x.responseType = 'blob';
x.open('get', 'http://stackoverflow.com');
x.onload = function() {
var fileReader = new FileReader();
fileReader.onloadend = function() {
// fileReader.result is a data-URL (string)
window.open(fileReader.result);
};
// x.response is a Blob object
fileReader.readAsDataURL(x.response);
};
x.send();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…