In Google Docs you can open outline pane and see all headers in the document, you can also click on an header and the view will scroll to header.
My question is how simulate mouse click programmatically with JS in Chrome extention, to scroll the view to the desired header?
I tryed following code but nothing hapend:
// usage: eventFire(document.getElementById('mytest1'), 'click');
function eventFire(el, etype) {
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
The headers is an div
elements with class="navigation-item-content navigation-item-level-2"
, When I look in chrome dev tools > event listeners, these elements do not have any event listeners.
In Google Docs you can open outline pane and see all headers in the document, you can also click on an header and the view will scroll to header.
My question is how simulate mouse click programmatically with JS in Chrome extention, to scroll the view to the desired header?
I tryed following code but nothing hapend:
// usage: eventFire(document.getElementById('mytest1'), 'click');
function eventFire(el, etype) {
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
The headers is an div
elements with class="navigation-item-content navigation-item-level-2"
, When I look in chrome dev tools > event listeners, these elements do not have any event listeners.
- 1 See this answer – Iván Nokonoko Commented Aug 17, 2018 at 8:05
- @IvánNokonoko It works! Thank you very much! – codeDom Commented Aug 17, 2018 at 9:27
1 Answer
Reset to default 11 +50From this answer:
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 element:
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 elementToClick = document.querySelector('#mytest1');
var box = elementToClick.getBoundingClientRect(),
coordX = box.left + (box.right - box.left) / 2,
coordY = box.top + (box.bottom - box.top) / 2;
simulateMouseEvent (elementToClick, "mousedown", coordX, coordY);
simulateMouseEvent (elementToClick, "mouseup", coordX, coordY);
simulateMouseEvent (elementToClick, "click", coordX, coordY);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744870982a4598258.html
评论列表(0条)