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.