Create a TamperMonkey script to create a copy text button for each <div>
- Assistant
Hello! How can I assist you today?
- User
Create a TamperMonkey script to create a copy text button for each
- Assistant
Hello! How can I assist you today?
Create a TamperMonkey script to create a copy text button for each
Sure! TamperMonkey is a great way to customize web pages with your own JavaScript. Below is a script that adds a "Copy Text" button to each div element on the page. When you click the button, it copies the text content of that div to the clipboard.
Here's the script:
// ==UserScript== // @name Copy Text Button for Divs // @namespace http://tampermonkey.net/ // @version 1.0 // @description Adds a "Copy Text" button to each div to copy its content to clipboard // @author Your Name // @match :///* // @grant GM_addStyle // ==/UserScript==
(function() { 'use strict';
// Function to copy text to clipboard
function copyTextToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
// Add copy button to each div
const divs = document.querySelectorAll('div');
divs.forEach(div => {
const button = document.createElement('button');
button.textContent = 'Copy Text';
button.style.margin = '5px';
button.addEventListener('click', () => {
copyTextToClipboard(div.textContent);
});
div.insertAdjacentElement('beforebegin', button);
});
// Optional: Add custom styles to the button
GM_addStyle(`
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 5px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 4px;
}
`);
})();
Explanation:
Metadata Block:
@name: The name of the script.@namespace: A namespace to avoid conflicts.@version: Version of the script.@description: Short description of what the script does.@author: Your name (or nickname).@match: URL pattern where the script will run. *://*/* means all URLs.@grant: Permissions the script needs. GM_addStyle is used to add custom styles.Functions and Logic:
copyTextToClipboard(text): Copies the given text to the clipboard using a textarea.div elements and for each div, create a button with 'Copy Text' as the label.div when clicked.div.GM_addStyle.How to Use:
Now, whenever you visit a webpage, you should see a "Copy Text" button adjacent to each div element. Clicking on the button will copy the div's content to your clipboard.
Feel free to modify the style and logic as needed for your specific use case!