How can I run this script when the extension icon is clicked?

60 views
Skip to first unread message

Eric Abraham

unread,
Sep 27, 2022, 12:40:08 AM9/27/22
to Chromium Extensions
I want to run this script when my extension icon will be clicked. How can I do that? I'm using Manifest Version 3.

let element = document.getElementsByClassName("caap5, caap6");
var vOuterText = element[0].outerText;
console.log(vOuterText);

//copy text
const textarea = document.body.appendChild(document.createElement('textarea'));
textarea.value = vOuterText;
textarea.focus();
textarea.select();
document.execCommand('copy');
textarea.remove();

wOxxOm

unread,
Sep 27, 2022, 5:30:55 AM9/27/22
to Chromium Extensions, Eric Abraham
Put your code in content.js, add a new background.js like this:

chrome.action.onClicked.addListener(tab => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    files: ['content.js'],
  });
});

and declare background.js in manifest.json:

"background": {
  "service_worker": "background.js"
}

Eric Abraham

unread,
Sep 27, 2022, 2:02:55 PM9/27/22
to Chromium Extensions, wOxxOm, Eric Abraham
Did exactly what you said.
Getting:
Uncaught TypeError: Cannot read properties of undefined (reading 'onClicked')

Screenshot_1.jpg

wOxxOm

unread,
Sep 27, 2022, 2:13:36 PM9/27/22
to Chromium Extensions, Eric Abraham, wOxxOm
Well, you can google up an error message to see how it's solved, it's often a trivial fix e.g. in this case you need to add "action": {} to manifest.json.

Eric Abraham

unread,
Sep 28, 2022, 1:50:08 AM9/28/22
to Chromium Extensions, wOxxOm, Eric Abraham
Thanks brother. You're awesome.
It works.

Thanks again. ❤️

Reply all
Reply to author
Forward
0 new messages