我正在为学校创建一个chrome扩展(所以老师可以监控学生们对他们的Chromebook做了什么)。
我已经使用了chrome.tabs.captureVisibleTab
字符串,在那里我遇到了我的新问题:< br> 如何将该屏幕截图保存到文件中?(必须在后台保存,否则学生可以阻止它)
由于
答案 0 :(得分:1)
是的,你当然可以。如何做到这一点非常有趣。
manifest.json 文件:
{
"name": "Screenshot Extension",
"manifest_version": 2,
"version": "1.0",
"description": "Save web page screenshots to image files by one click",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [
{
"js": ["content.js"],
"matches" : ["<all_urls>"]
}
],
"browser_action": {
"default_icon": "extension_icon.png",
"default_title": "Screenshot of this page"
},
"permissions": ["activeTab", "tabs", "<all_urls>"]
}
content.js 文件:
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.ready === "ready") {
if (confirm('Do you want to have a capture of this screen?')) {
sendResponse({download : "download"});
}
}
});
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) {
if (response.download === "download") {
screenshot.saveScreenshot();
}
else {
screenshot.data = '';
}
});
});
});
});
}
};
screenshot.init();
background.js
控制扩展程序的逻辑,而
content.js
与网页互动。他们发送消息给
彼此沟通。
如果您希望扩展程序适用于所有网站,则必须设置权限<all_urls>