Cannot trigger click using jQuery in Chrome extension

I am trying to make a Chrome extension with a single line of jQuery code, but this does not work. I am trying to trigger a click on an element.

The chrome console does not show any errors at all, and when I put jQuery code ONLY in the console, it works fine.

My code is:

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 also downloaded the jquery-2.1.3.min.js and jquery-2.1.3.min.js file into the extensions folder.

Can anyone explain why this is not working ???

-2
javascript jquery google-chrome google-chrome-extension
source share
1 answer

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

So your content script has its own copy of jQuery. The way jQuery .click() works is to save a list of event handlers triggered by a mouse click.

.. and you can see the problem already. The content of the jQuery copy script is not aware of the page copy list for handlers, and cannot run them .

This, by the way, explains why this works when you put it in the console - by default, the console runs in the context of the page and starts a copy of the jQuery page.

There are ways to overcome this, but the easiest one for your task is to fix the proper DOM event that will be caught by the page code. See this question for an example.

+4
source share

All Articles