0

I'm writing a chrome extension in which i need to click on a item on the webpage. The item can be found with document.getElementsByClassName("className")[0].click() but if I run this in the popup, it searches for the item in the popup menu instead. How can I make it return and click the item in the webpage?

1 Answers1

0

You should make a content script and use that to perform the click. Content scripts are loaded in the context of the HTML page, as opposed to the extension popup.

You can message between your content script and your main extension code by using the messaging API.

Your extension code could send a message to the content script like this:


// Query the active tab in the current window (there will only be one)
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {

  // Send a message to that tab (found as tabs[0]), 
  chrome.tabs.sendMessage(tabs[0].id, {message: "perform_click"}, function(response) {
    console.log("Click performed.");
  });
});

And your content script could handle the request like this:


// Listen for events from the background script (main part of the extension)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  // This function will be called in the content script to handle messages received from the main extension code.

  // If the extension is requesting a click, we do that here
  if (request.message == "perform_click") {
    document.getElementsByClassName("className")[0].click()
  }
});
brads3290
  • 1,142
  • 1
  • 9
  • 17