为什么我的Chrome扩展程序无法单击Google文档中的“新建评论”按钮?

时间:2019-08-21 12:55:24

标签: javascript google-chrome-extension google-docs

直到最近,我的Chrome扩展程序通过内容脚本,都能够找到并以编程方式单击在Google文档中突出显示文本后(在“编辑”模式下)出现的“新评论”按钮。

突出显示以下是出现的按钮:

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

我的代码仍然“看到”该元素-如果需要,我可以将其变为红色。

但是我用来创建“点击”的Click处理程序不再起作用。这是简单的js:

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

Google文档(对此元素)进行了哪些更改,导致我的程序化点击失败?

在此先感谢您的指导/帮助!

1 个答案:

答案 0 :(得分:1)

来自this answer

尝试使用此代码;它通过快速连续的mousedown,mouseup和在按钮中央触发的click事件来模拟鼠标在元素上的左击:

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