Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a chrome extension from a click button?

After a lot of times spend to find the solution, i'm here to ask your help.

I have a simple chrome extension, and what I try to do is simple: Detect on the page when a button is clicked, then, open the extension popup.html.

A good example is MetaMask, the html page can open the popup to connect the wallet, send transaction ...

Thank you !

like image 776
SolidyJS Avatar asked Sep 15 '25 13:09

SolidyJS


1 Answers

  1. Run a content script on the page and send a message to the background when the button is clicked.
// Content Script

button.addEventListener("click", () => {
  chrome.runtime.sendMessage("OpenPopup")
})
  1. Catch the message in the background and create a window with your popup URL. Provide a "top" and a "left" value to place it at the top right of the users' screen. Use the type "popup" to get rid of the stuff that is usually at the top of a window. Read more about the chrome.windows.create method here.
// Background Script

chrome.runtime.onMessage.addListener(request => {

  if (request == "OpenPopup") {

      chrome.windows.create({
          url: "popup.html",
          type: "popup",
          focused: true,
          width: 400,
          height: 600,
          top: 0,
          left: screen.width - 400,
      }, () => {
          console.log("Opened popup!")
      })

  }

})
like image 89
Jakob Avatar answered Sep 18 '25 09:09

Jakob