如何从javascript调用谷歌浏览器屏幕截图扩展?

时间:2017-07-29 08:41:56

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

我有一个谷歌浏览器扩展程序,可生成网页活动标签的屏幕截图并下载。启用后,它在chrome上运行正常。我希望在我的网页上点击按钮生成和下载相同的屏幕截图。如何从网页上调用该扩展程序? 我的扩展代码在这里:

的manifest.json

    {
      "name": "Screenshot Extension",
      "version": "1.0",
      "description": "A simple screenshot extension",
      "background": {
          "persistent": false,
          "scripts": ["background.js"]
     },
     "content_scripts": [
    {
        "matches" : ["<all_urls>"],
        "js": ["content.js"]
    }
    ],
    "browser_action": {
    "default_icon": "camera.png",
    "default_title": "Screenshot"
    },
    "permissions": ["tabs", "<all_urls>", "activeTab"],
    "manifest_version": 2
    }

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.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.captureVisibleTab(null, {
            format : "png",
            quality : 100
        }, function(data) {
            screenshot.data = data;

            // send an alert message to webpage
            chrome.tabs.query({
                active : true,
                currentWindow : true
            }, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {ready : "ready"}, 
            function(response) {

                        screenshot.saveScreenshot();

                                        });
            }); 

            });
            });
            }
         };

        screenshot.init();

content.js

   chrome.extension.onMessage.addListener(function(msg, sender, 
   sendResponse) {

   if (msg.ready === "ready") {
    if (confirm('Do you want to capture the screen?')) {
        sendResponse({download : "download"});
    }
   }

   }); 

请帮忙。

0 个答案:

没有答案