Skip to content

Instantly share code, notes, and snippets.

@ClearlyKyle
Last active April 21, 2024 20:01
Show Gist options
  • Save ClearlyKyle/f7a70b1d4c713849ea219cc9863ace16 to your computer and use it in GitHub Desktop.
Save ClearlyKyle/f7a70b1d4c713849ea219cc9863ace16 to your computer and use it in GitHub Desktop.
Basic chrome extension that sends a message to the background script, then captures a screenshot of the current web-page
// Function to convert data URL to Blob
function data_URL_to_blob(data_url)
{
var arr = data_url.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--)
{
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
function take_screenshot()
{
console.log("Taking a screenshot...");
chrome.tabs.captureVisibleTab(null, { format: "png" }, (data_url) =>
{
console.log(data_url);
if (data_url == undefined)
return;
// Create a Blob from the data URL
var blob = data_URL_to_blob(data_url);
// Create a FileReader to read the Blob
var reader = new FileReader();
// Callback function for FileReader
reader.onload = function (event)
{
// Use chrome.downloads API to save the file
// prompting the user for a location
chrome.downloads.download({
url: event.target.result,
filename: "screenshot.png",
saveAs: true
});
};
// Read the Blob as a data URL
reader.readAsDataURL(blob);
});
return true;
}
chrome.runtime.onMessage.addListener(async function (request, sender)
{
if (request.msg === "screenshot")
{
take_screenshot(sender.tab.windowId);
}
});
console.log("Content script loaded!");
function take_screenshot()
{
console.log("Button is clicked");
chrome.runtime.sendMessage({msg : "screenshot"});
}
// Function to be executed once the page is loaded
function add_my_button()
{
console.log("Adding my button");
// Create a button element
const button = document.createElement("button");
button.innerText = "Screenshot";
button.style.position = 'fixed';
button.style.top = '10px';
button.style.left = '10px';
// Add an event listener to the button
button.addEventListener("click", take_screenshot);
// Append the button to the body of the page
document.body.appendChild(button);
return true;
}
window.addEventListener('load', add_my_button);
{
"manifest_version": 3,
"name": "Basic Screenhot",
"description": "Save an image of the current webpage using a message from content_script",
"version": "1.0",
"author": "@clearlykyle",
"permissions": [
"downloads"
],
"content_scripts": [
{
"matches": [
"https://*.wikipedia.org/*"
],
"all_frames": true,
"js": [
"content_script.js"
],
"run_at": "document_idle"
}
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "background.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment