1

I want to inject custom code to the web page after the user clicks on my chrome extension icon or clicks on a button inside the chrome extension popup. I have seen this feature been done in **loom **(Screen Recorder) in which when the user clicks on the loom icon, it shows a popup for loading and then injects its own custom code to the user's web page in the image, it injects its own code inside the DOM to start recording

I also want to do something like this, but not sure how exactly I should go about this,

I try this :-

manifest.json

{
    "manifest_version": 3,
    "name": "My Extension",
    "version": "1.0",
    "description": "Description of my extension",
    "permissions": ["activeTab"],
    "content_scripts": [
        {
          "matches": ["<all_urls>"],
          "js": ["content.js"]
        }
      ],
      "background": {
        "service_worker": "background.js"
      }
    
  }

background.js

chrome.action.onClicked.addListener(async function(tab) {
    chrome.tabs.executeScript({
        file: "content.js"
      });
  });

content.js

  const overlayButton = document.createElement("button");
  overlayButton.innerText = "Record";
  
  // Add a click event listener to the button
  overlayButton.addEventListener("click", function() {
    // Code to handle button click event
  });
  
  // Add the overlay button to the page
  document.body.appendChild(overlayButton);

But I got this error in the chrome extension :-

enter image description here

I am not really sure what is best practise to inject my own code inside the user's web page. Also how should I do it without writing the .innerHTML and the whole html inside it

Thank you :)

  • To use `action` you need to add `"action": {}` to manifest.json. There's also no chrome.tabs.executeScript in ManifestV3, it's chrome.scripting.executeScript and you need to add `scripting` to `permissions` in manifest.json. – wOxxOm Mar 08 '23 at 14:07
  • @wOxxOm I added action: {} in my manifest and changed the execute script, but now when I click on the extension, nothing happen? – Darwin Swartz Mar 08 '23 at 17:49
  • Debug it. [How to see background.js console?](/a/10258029) Also don't forget to click the reload icon in chrome://extensions. – wOxxOm Mar 08 '23 at 18:26
  • @wOxxOm, I am still trying to figure it out, but I need your advice on something, is it more useful to create the chrome extension like loom using Reactjs or with raw js, HTML and CSS? – Darwin Swartz Mar 09 '23 at 06:30
  • for v3: remove content_script from manifest and in "action" add this "action": { "default_icon": { "16": "images/icon-32.png", "24": "images/icon-32.png", "32": "images/icon-32.png" } }, this will let icon to have a event and now in background.js add this code chrome.action.onClicked.addListener((tab) => { chrome.scripting.executeScript({ target: {tabId: tab.id}, files: ['content.js'] }); }); – Sanjay RD Jun 27 '23 at 18:02

0 Answers0