TamperMonkey script to copy text from the last load page
- User
TamperMonkey script to copy text from the last load page
- Assistant
TamperMonkey script to copy text from the last load page
Creating a Tampermonkey script to copy text from the last loaded page involves a few steps. Here’s a simple script to achieve this task:
DOMContentLoaded event to detect page loading.Please note that for security reasons, browser scripts may have limitations and might not work seamlessly for all sites, particularly those with strong Content Security Policies (CSP) or dynamic content loading (e.g., single-page applications).
Here’s a basic example script:
// ==UserScript==
// @name Copy Last Page Text
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Copy text from the last loaded page
// @author
// @match *://*/*
// @grant GM_setClipboard
// @grant GM_setValue
// @grant GM_getValue
// ==/UserScript==
(function () {
'use strict';
// Function to copy text to clipboard
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
// Wait for the page to be fully loaded
window.addEventListener('load', () => {
// Get the text from the page
let pageText = document.body.innerText;
// Store the text locally
GM_setValue('lastPageText', pageText);
// Log the saved text to the console
console.log('Last page text saved:', pageText);
// Optionally copy the text to the clipboard (if desired)
copyText(pageText);
});
// To retrieve the saved text from storage
window.addEventListener('keydown', (e) => {
// Check if the Ctrl+Shift+L keys are pressed together
if (e.ctrlKey && e.shiftKey && e.key === 'L') {
let lastText = GM_getValue('lastPageText', '');
console.log('Last saved page text:', lastText);
// Copy retrieved text to the clipboard
copyText(lastText);
}
});
})();
Install Tampermonkey: Ensure you have Tampermonkey installed in your browser.
Create a new script: Open the Tampermonkey dashboard and create a new script.
Copy-Paste the Script: Copy the above script into the Tampermonkey editor and save it.
Configure Permissions: This script uses GM_setClipboard, GM_setValue, and GM_getValue for setting clipboard content and saving/retrieving text. Ensure these permissions are granted.
Usage:
Ctrl+Shift+L to log and copy the last saved text to your clipboard.Disclaimer: Always ensure you have appropriate permissions to scrape or copy content from websites. Some websites might have legal or technical protections against automated scraping or copying. Respect the terms of service for each site.