【问题标题】:Chrome Extension: Automatically download a screenshot taken with 'chrome.tabs.captureVisibleTab'Chrome 扩展程序:自动下载使用“chrome.tabs.captureVisibleTab”截取的屏幕截图
【发布时间】:2015-03-26 09:53:13
【问题描述】:

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

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

我以前用blob 做过类似的事情,但我完全不知道如何下载图像以及如何自动下载。

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

【问题讨论】:

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


    【解决方案1】:

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

    我创建并测试的示例代码适用于我:

    内容脚本(myscript.js):

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

    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();
    

    另外请记住在清单文件中注册您的内容脚本的代码和权限:

    "permissions": ["<all_urls>","tabs"],
        "content_scripts": [
        {
          "matches": ["http://www.particularpageone.com/*", "http://www.particularpagetwo.com/*"],
          "js": ["myscript.js"]
        }
      ]
    

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

    【讨论】:

    • 我用你的代码下载了页面的自动截图。但它总是提醒我保存文件。我不想发出警报并将其保存以自动下载...我正在使用 mac 和 chrome 浏览器(两者都是最新的)。请有任何想法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2022-08-13
    相关资源
    最近更新 更多