简体   繁体   中英

Chrome Extension: How to get Element from active Tab Page

I'm trying to make a chrome-extension. There is a button on my popup.html which clicks on an element in the active tab. In theory I think I understand how to do that but right now I'm stuck here:


HTML on the Site:

<td class="confirmButtons">
<form action="modcp.php" method="post">
<input class="formAction" type="hidden" name="" value="">
<ul>
<li class="button"><a href="javascript:void(0);" class="formAction" rel="confirm" tabindex="2"><strong>Ja</strong></a></li>
</ul>

<ul class="buttonGroup">
<li class="first"></li>
<li class="button"><a href="javascript:void(0);" class="formAction" rel="cancel" tabindex="2"><strong>Nein</strong></a></li><a href="javascript:void(0);" class="formAction" rel="cancel" tabindex="2">
<li class="last"></li>
</a></ul></form></td>

The Code I use in my content_script.js:

function clickJa() {
    console.log("clickJA");
    var confirmButton = document.getElementsByClassName("confirmButtons"); 
    console.log(confirmButton);        
}

Now, my Problem: When I paste the Code in the Console it returns an Array with 1 element - thats fine. When I press my button in the extension ut returns an Array with 0 elements - thats not good and I have no Idea whats wrong... do you have some Ideas?

Greetings and thanks for every Idea & answer Lime

As said in the comments, we need more details. However, let's try to understand:

  • You have a button in your popup page
  • When you click on this button in your button page, you want an element to be clicked on in the active page.

From where do you call the function:

clickJa()

From the popup page?

If it is from the popup page, then the function is executed inside the popup page, and therefore, you will not have your element. (As it is not in the popup page but on the active tab)

If your goal is only to click on an element from the popup page, then maybe the simplest thing to do is something like:

chrome.tabs.executeScript( {
    code: "document.getElementsByClassName(\"confirmButtons\").click();"
}, function() {
      console.log("Element clicked !");
});

(Not tested though)

More info about script execution: https://developer.chrome.com/extensions/tabs#method-executeScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM