如何在 Chrome 扩展程序中使用 JavaScript 触发“isTrusted=true”点击事件?

问题描述 投票:0回答:3

我正在尝试使用 Chrome 扩展来模拟用户点击和鼠标移动。

例如:
在我的内容脚本中,有一个按钮单击。

document.querySelector("SOME_SELECTOR").click();

此行触发具有以下属性的单击事件:

MouseEvent {isTrusted: false}

如何触发 isTrusted 属性为 true 的 MouseEvent?

javascript google-chrome-extension dom-events
3个回答
21
投票

您可以使用调试器界面注入可信事件。

chrome.debugger.attach(target, "1.2", function() {
    chrome.debugger.sendCommand(target, "Input.dispatchMouseEvent", arguments)
})

https://developer.chrome.com/extensions/debugger

https://chromedevtools.github.io/devtools-protocol/1-2/Input


3
投票

我不确定这是否可能,因为它是一个只读属性,准确地表示您要伪造的内容,即事件是否源自最终用户或脚本。 曾经存在基于浏览器的差异(IE 曾经将所有事件视为可信),但我不知道情况是否仍然如此。

https://developer.mozilla.org/en-US/docs/Web/API/Event

可能仍有解决此问题的方法,如本主题中针对 Firefox 所提到的:Firefox 扩展生成的事件“可信”吗?

但是您必须查看 chrome 文档,以检查它们是否具有将事件委托回窗口的类似方法,因为它确实提到扩展事件在某些情况下是/可以被信任的。


0
投票

您可以使用此代码。 isTrusted 事件将为 true。

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status == "complete") {
    if (tab.url.indexOf("instagram") != -1) {
    chrome.debugger.attach( {tabId: tab.id}, "1.2", async function() {
        setTimeout(function(){
        //opts = {type: "mousePressed", button: "left", x: 557, y: 204, clickCount: 1};
        //chrome.debugger.sendCommand({tabId: tab.id}, "Input.dispatchMouseEvent", opts);
        //opts0 = {type: "mouseReleased", button: "left", x: 557, y: 204, clickCount: 1};
        //chrome.debugger.sendCommand({tabId: tab.id}, "Input.dispatchMouseEvent", opts0);

        opts1 = {type: "keyDown", code: "KeyA", key: "a", text: "a"}
        chrome.debugger.sendCommand({tabId: tab.id}, "Input.dispatchKeyEvent", opts1);
        chrome.debugger.sendCommand({tabId: tab.id}, "Input.dispatchKeyEvent", {type: "keyDown", code: "KeyB", key: "b", text: "b"});

        //opts2 = {type: "keyUp", code: "KeyA", key: "a"}
        //chrome.debugger.sendCommand({tabId: tab.id}, "Input.dispatchKeyEvent", opts2);
    }, 5000);

    })
}
  
}});
© www.soinside.com 2019 - 2024. All rights reserved.