Chrome扩展程序:自动下载使用'chrome.tabs.captureVisibleTab'拍摄的屏幕截图

JVG*_*JVG 0 javascript screenshot google-chrome google-chrome-extension

我是Chrome扩展程序/自动下载的新手.我有一个背景页面,其中包含可见网页的屏幕截图chrome.tabs.captureVisibleTab().在我的弹出窗口中,我有:

chrome.tabs.captureVisibleTab(null, {}, function (image) {
  // Here I want to automatically download the image
});
Run Code Online (Sandbox Code Playgroud)

我已经做了类似的事情blob,但我完全不知道如何下载图像以及如何自动完成.

在实践中,我希望我的Chrome扩展程序能够在加载特定页面时自动截图+下载图像(我猜这必须通过让我的内容脚本与我的后台页面对话来实现,对吗?)

Day*_*ang 6

是的,正如您所说,您可以使用消息传递来完成它.通过内容脚本检测特定页面上的开关,然后与后台页面聊天以捕获该页面的屏幕截图.您的内容脚本应使用发送消息chrome.runtime.sendMessage,后台页面应使用chrome.runtime.onMessage.addListener以下方式监听:

我创建和测试的示例代码与我合作:

内容脚本(myscript.js):

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {

  });
Run Code Online (Sandbox Code Playgroud)

Background.js:

var screenshot = {
  content : document.createElement("canvas"),
  data : '',

  init : function() {
    this.initEvents();
  },
 saveScreenshot : function() {
    var image = new Image();
    image.onload = function() {
      var canvas = screenshot.content;
      canvas.width = image.width;
      canvas.height = image.height;
      var context = canvas.getContext("2d");
      context.drawImage(image, 0, 0);

      // save the image
      var link = document.createElement('a');
      link.download = "download.png";
      link.href = screenshot.content.toDataURL();
      link.click();
      screenshot.data = '';
    };
    image.src = screenshot.data; 
  },
initEvents : function() {
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.greeting == "hello") {
          chrome.tabs.captureVisibleTab(null, {format : "png"}, function(data) {
                screenshot.data = data;
                screenshot.saveScreenshot();

            }); 

        }
    });
  }
};
screenshot.init();
Run Code Online (Sandbox Code Playgroud)

还要记住在清单文件中注册内容脚本的代码和权限:

"permissions": ["<all_urls>","tabs"],
    "content_scripts": [
    {
      "matches": ["http://www.particularpageone.com/*", "http://www.particularpagetwo.com/*"],
      "js": ["myscript.js"]
    }
  ]
Run Code Online (Sandbox Code Playgroud)

它会捕获屏幕截图并在加载特定页面时自动将图像下载为.png.干杯!