简体   繁体   中英

Code works in console but not in Chrome extension?

I'm trying to click an element with an < a > tag using jquery. It works in the Chrome console, but it doesn't work from the extension. What am I doing wrong?

This is what I'm trying to 'click':

<a href="" id="roblox-confirm-btn" class="btn-large btn-negative">Yes<span class="btn-text">Yes</span></a>

This is what I use in the console, it works fine:

var thing = $("a#roblox-confirm-btn")
thing.click()

This is what I use in the chrome background.js, it doesn't work:

setTimeout(function() {
    //NOTE: 'click?' IS being printed into the console, and I'm getting no error
    console.log("click?")
    var thing = $("a#roblox-confirm-btn")
    thing.click()
}, 2000)

The HTML and its events are in the context of page or content, so you need to include the same in content script and inject it as part of DOM so then it gets executed. Also, I assume that you have included the jQuery script without fail as you are using it($).

You can try this fix:

Step 1: Define that code in content_script.js

setTimeout(function() {
    console.log("click?")
    $("a#roblox-confirm-btn").click();
}, 2000);

Step 2: Declare it in manifest.json

{
  ...
  "content_scripts": [{
      "js": ["js/jquery.js", "js/content_script.js"]
    }]
}

Hope it helps.

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