0

Until recently my Chrome Extension, through a Content Script, was able to find and programmatically click the 'new comment' button that appears after highlighting text in a Google Doc (in Edit mode).

Here's the button that appears when you highlight:

<div id="docs-instant-button-bubble" class="docs-material docs-instant- 
button-bubble-transformation-ltr docs-instant-button-visible" instant- 
role="button" tabindex="-1" aria-hidden="true" aria-label="Add a instant- 
comment" data-tooltip="Add a comment" style="top: 352.8px; opacity: 1; instant- 
background-color: red;"><div class="docs-instant-button-bubble-icon-instant- 
container"><span class="docs-instant-button-bubble-icon docos-icon-img instant- 
docos-icon-img-hdpi docos-instant-icon-img docos-icon-instant-docos-ltr instant- 
docos-instant-button-bubble-icon"></span></div></div>

My code still 'sees' this Element - I can turn it red if I want.

But the Click handler I was using, to create a 'Click' does not work anymore. Here is the simple js:

document.getElementById("docs-instant-button-bubble").click();

What changed in Google Docs (to this Element) that makes my programmatic click fail?

Thank you in advance for any guidance/help!

11teenth
  • 1,853
  • 1
  • 15
  • 28
  • Try yourElement.dispatchEvent(new MouseEvent('click', {bubbles: true})) – wOxxOm Aug 21 '19 at 13:29
  • Try with [this method](https://stackoverflow.com/a/43331339/3930351). – Iván Nokonoko Aug 21 '19 at 19:58
  • @wOxxOm, I changed to: var bubbleElem = $("#docs-instant-button-bubble"); bubbleElem.dispatchEvent(new MouseEvent('click', {bubbles: true})) And got: Error handling response: TypeError: bubbleElem.dispatchEvent is not a function – 11teenth Aug 22 '19 at 01:06
  • @IvánNokonoko - that works beautifully (so far)!!! Many thanks. Want to write it up as an answer? – 11teenth Aug 22 '19 at 01:59
  • bubbleElem is not an element, it's a jQuery wrapper so you need bubbleElem[0] to access the actual element. – wOxxOm Aug 22 '19 at 03:40

1 Answers1

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 button:

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 theButton = document.querySelector('ul form button');

var box = theButton.getBoundingClientRect(),
    coordX = box.left + (box.right - box.left) / 2,
    coordY = box.top + (box.bottom - box.top) / 2;

simulateMouseEvent (theButton, "mousedown", coordX, coordY);
simulateMouseEvent (theButton, "mouseup", coordX, coordY);
simulateMouseEvent (theButton, "click", coordX, coordY);
Iván Nokonoko
  • 4,888
  • 2
  • 19
  • 27