Chrome扩展程序 - 从背景到上下文脚本的Blob

时间:2017-04-26 23:31:31

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

我有一个chrome扩展程序,试图记录活动选项卡并将blob保存到本地存储。

根据用户发出的命令调用chrome.tabCapture,5秒后,录制停止并从录制的块中创建新的blob,继续下载文件。

当下载文件时,文件为0字节,当之前放置断点时,检查blob大于0字节。最终尝试将blob返回到sendResponse回调中的上下文脚本。

如果在下载或重新上传到上下文脚本时blob为空的原因是什么,那就太好了。

遵循以下文档:https://developers.google.com/web/updates/2016/01/mediarecorder

background.js

chrome.tabCapture.capture(captureOptions, function (stream) {
    if (!stream)
        return;
    var recordedChunks = [];
    var options = {
        mimeType: 'video/webm; codecs=vp9',
    };

    var mediaRecorder = new MediaRecorder(stream, options);
    mediaRecorder.ondataavailable = function (event) {
        if (event.data.size > 0) {
            recordedChunks.push(event.data);
        }
    }
    mediaRecorder.start();
    setTimeout(function(){
        stopRecording(stream, mediaRecorder, recordedChunks);
    }, 5000);
})


 var stopRecording = function (stream, mediaRecorder, recordedChunks) {
   mediaRecorder.stop();
   var blob = new Blob(recordedChunks, {
       type: 'video/webm'
   });
   var url = URL.createObjectURL(blob);
   var a = document.createElement('a');
   document.body.appendChild(a);
   a.style = 'display: none';
   a.href = url;
   a.download = 'test.webm';
   a.click();
   URL.revokeObjectURL(url);
   stream.getVideoTracks()[0].stop();
 };

1 个答案:

答案 0 :(得分:0)

我通过在ondataavailable回调中下载文件来实现它:

<强> background.js:

chrome.tabCapture.capture(captureOptions, function (stream) {
    if (!stream)
        return;
    var recordedChunks = [];
    var options = {
        mimeType: 'video/webm; codecs=vp9',
    };

    var mediaRecorder = new MediaRecorder(stream, options);
    mediaRecorder.ondataavailable = function (event) {
        if (event.data.size > 0) {
          var url = URL.createObjectURL(event.data);
          var a = document.createElement('a');
          document.body.appendChild(a);
          a.style = 'display: none';
          a.href = url;
          a.download = 'test.webm';
          a.click();
          URL.revokeObjectURL(url);
        }
    }
    mediaRecorder.start();
    setTimeout(function(){
        stopRecording(stream, mediaRecorder, recordedChunks);
    }, 5000);
})


 var stopRecording = function (stream, mediaRecorder, recordedChunks) {
   mediaRecorder.stop();
   stream.getVideoTracks()[0].stop();
 };