EN
How to make simple Google Chrome Extension
0
points
In this article, we would like to show you how to make a simple Chrome Extension.
Below we present a simple extension that after pressing Alt + C will copy the title and URL of the currently opened tab and put them in the clipboard.
Note:
Check out this article, to see how to load your extension into Chrome:
How to load extension into Google Chrome
Project structure
example_chrome_extension/
|
+-- manifest.json
|
+-- background.js
manifest.json
{
"name": "Copy tool",
"manifest_version": 3,
"version": "0.1",
"description": "Copy title and URL of current website",
"commands": {
"copy": {
"suggested_key": {
"default": "Alt+C"
},
"description": "Copy shortcut"
}
},
"permissions": [
"activeTab",
"scripting",
"tabs"
],
"background": {
"service_worker": "background.js"
}
}
background.js
const copyTitleAndURL = () => {
const dataToClipboard = document.title + '\n' + window.location.toString();
const temporaryElement = document.createElement('textarea');
temporaryElement.value = dataToClipboard;
document.body.appendChild(temporaryElement);
temporaryElement.select();
document.execCommand('Copy');
document.body.removeChild(temporaryElement);
};
chrome.commands.onCommand.addListener(async (command) => {
const [tab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
if (command === 'copy') {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: copyTitleAndURL,
});
}
});