Can't trigger click with jQuery in a Chrome extension

I am trying to make a Chrome extension with one line of jQuery code but it doesn't work. I'm trying to trigger a click on an element.

The console of chrome doesn't show any error at all, and when I put ONLY the jQuery code in console it works fine.

My code:

content.js

$(document).ready(function() {
  $('.like_post:contains(Like)').click();
});

background.js

chrome.windows.getCurrent( function(currentWindow) {
  chrome.tabs.query({active: true, windowId: currentWindow.id}, function(activeTabs){
    chrome.tabs.executeScript(
      activeTabs[0].id, {file: 'jquery-2.1.3.min.js', allFrames: true}
    );
    chrome.tabs.executeScript(
      activeTabs[0].id, {file: 'content.js', allFrames: true}
    );
  });
  console.log(currentWindow.id);
});

manifest.json

{
  "name": "plugin name",
  "version": "0",
  "description": "What do I do as an extension",

  "manifest_version": 2,
  "browser_action": {
    "name": "project with jquery",
    "icons": ["icon.png"],
    "default_icon": "icon.png"
  },
  "content_scripts": [ {
    "js": [ "jquery-2.1.3.min.js", "background.js", "content.js" ],

    "matches": [ "http://*/*", "https://*/*"]
  }]
}

I have also downloaded the jquery-2.1.3.min.js file and have it in the extension folder.

Can anyone explain why it doesn't work???

Answers:

Answer

The root cause of the problem is that extension content scripts execute in an isolated world. One of the reasons for this is so that your code does not conflict with the page's code: for instance, you can use a different version of jQuery.

So, your content script has its own copy of jQuery. The way jQuery's .click() works is by maintaining a list of event handlers that are triggered by the click..

..and you may see the problem already. The content script's copy of jQuery is not aware of the page's copy list of handlers, and cannot trigger them.

That, by the way, explains why it works when you put it in the console - by default, console executes in the page's context and triggers the page's copy of jQuery.

There are ways to overcome this, but the most straightforward for your task is to emit a proper DOM event, that will be caught by the page's code. See this question for an example.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.