How to add automatic click feature in chrome exten

2019-07-28 23:31发布

问题:

I am creating a chrome extension, and need to click on the first link automatically for some time. Is it possible to add automatic click feature in chrome extension??

回答1:

If you don't care about mouse coordinates, you can use this:

var trigger = document.createEvent("Event");
trigger.initEvent("click", true, true);
element.dispatchEvent(trigger);

"element" should be the DOM node you want to trigger the click on. If you want to also specify a particular X/Y coordinate, you could use this:

var x = 0,
    y = 0;

var trigger = document.createEvent("MouseEvent");
trigger.initMouseEvent("click", true, true, null, 0, x, y, x, y, false, false, false, false, 0, null);
element.dispatchEvent(trigger);

Change x and y to what you want ...or just use jQuery, like npdoty said.



回答2:

jQuery has a nice trigger function for just such a situation (jQuery docs), even a shortened form just for the click event, and that pairs nicely with the :first pseudo-selector.

$('a:first').click();

You can probably do this in pure JavaScript as well, using some combination of element.click() or dispatching events.