Недавно я разработал расширение Chrome, которое извлекает контент со страницы и отправляет его на сервер.
Использовался следующий подход:
- Загрузка файлов: например, получите свойство
src
элемента <img>
.
- Получить файл из кеша - используйте
XMLHttpRequest
со страницы фона.
- Используйте Web Worker на фоновой странице для обработки загрузки.
Примечание, чтобы взять контрольную сумму изображения, Crypto-JS: MD5 . Пример (где xhr
- это объект XMLHttpRequest
с responseType
, установленным на arraybuffer
, см. Демонстрационную версию Worker):
var md5sum = Crypto.MD5( new Uint8Array(xhr.response) );
Полный пример
// Example: Grab the first <img> from the document if it exists.
var img = document.images[0];
if (img) {
// Send the target of the image:
chrome.runtime.sendMessage({method: 'postUrl', url: img.src});
}
Фоновый скрипт (с рабочим)
chrome.runtime.onMessage.addListener(function(request) {
if (request.method == 'postUrl') {
var worker = new Worker('worker.js');
worker.postMessage(request.url);
}
});
Web Worker
// Define the FormData object for the Web worker:
importScripts('xhr2-FormData.js')
// Note: In a Web worker, the global object is called "self" instead of "window"
self.onmessage = function(event) {
var resourceUrl = event.data; // From the background page
var xhr = new XMLHttpRequest();
xhr.open('GET', resourceUrl, true);
// Response type arraybuffer - XMLHttpRequest 2
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (xhr.status == 200) {
nextStep(xhr.response);
}
};
xhr.send();
};
function nextStep(arrayBuffer) {
var xhr = new XMLHttpRequest();
// Using FormData polyfill for Web workers!
var fd = new FormData();
fd.append('server-method', 'upload');
// The native FormData.append method ONLY takes Blobs, Files or strings
// The FormData for Web workers polyfill can also deal with array buffers
fd.append('file', arrayBuffer);
xhr.open('POST', 'http://YOUR.DOMAIN.HERE/posturl.php', true);
// Transmit the form to the server
xhr.send(fd);
};
FormData
для работников сети POLYFILL
Веб-работники изначально не поддерживают объект FormData
, используемый для передачи форм multipart/form-data
. Вот почему я написал для него polyfill. Этот код должен быть включен в веб-работника, используя importScripts('xhr2-FormData.js')
.
Исходный код полифилла доступен по https://gist.github.com/Rob--W/8b5adedd84c0d36aba64
Файл манифеста:
{
"name": "Rob W - Demo: Scraping images and posting data",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["contentscript.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"permissions": ["http://*/*", "https://*/*"]
}
Соответствующая документация