Can't Trigger Click with Jquery in a Chrome Extension

Can't trigger click with jQuery in a Chrome extension

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.

How to trigger click on a button

Try with this code; it simulates a mouse left click on the element by a quick succession of mousedown, mouseup and click events fired in the center of the button:

var simulateMouseEvent = function(element, eventName, coordX, coordY) {
element.dispatchEvent(new MouseEvent(eventName, {
view: window,
bubbles: true,
cancelable: true,
clientX: coordX,
clientY: coordY,
button: 0
}));
};

var theButton = document.querySelector('ul form button');

var box = theButton.getBoundingClientRect(),
coordX = box.left + (box.right - box.left) / 2,
coordY = box.top + (box.bottom - box.top) / 2;

simulateMouseEvent (theButton, "mousedown", coordX, coordY);
simulateMouseEvent (theButton, "mouseup", coordX, coordY);
simulateMouseEvent (theButton, "click", coordX, coordY);

Trigger click not working

The code works properly, but the "click" event triggered programmatically will not open the select option list.

See Is it possible to use JS to open an HTML select to show its option list?

You can test that it works by adding your own onclick event for that element and then triggering the click event.

Event not firing inside Chrome Extension using JQuery and Javascript

You are using the class delete not an ID

In this part of your code that you are appending on your #divIncome:

<label for='newBox'>New Label</label>
<div>
<span>
<input type='text' id='newBox' style='width:95%' />
</span>
<span style='float:right' class='delete' id='delete'>
<i class='material-icons delete' style='font-size:20px;'>delete</i>
</span>

You are using delete as class on both <span> and <i> element's
Just trigger they like this:

$(document).on("click", ".delete", function(){
//Do your stuff
});

And when using dynamic generated elements, is important to trigger their events using $(document).on(), otherwise it will not be triggered

See more W33 Selectors Reference and JQuery Documentation



Related Topics



Leave a reply



Submit