Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 871
google dev Avatar asked Aug 14 '18 19:08

google dev


People also ask

How do you outline text in Google Docs?

Here's how to use the Outline tool, on a Computer and within the Google Docs editor. To open the outline, click Tools > Document outline. The outline will open on the left.


1 Answers

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);
like image 188
Iván Nokonoko Avatar answered Nov 15 '22 07:11

Iván Nokonoko