Google Docs - programmatically send mouse click to an item in outline pane

て烟熏妆下的殇ゞ 提交于 2020-01-14 13:09:24

问题


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:


From 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);


来源:https://stackoverflow.com/questions/51848258/google-docs-programmatically-send-mouse-click-to-an-item-in-outline-pane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!