Chrome 扩展程序的内容脚本能否保证 DOM 事件是由用户发起的?

Can a Chrome extension's content script guarantee that a DOM event was user-initiated?

我有一个扩展程序,可以将 HTML 元素注入页面并监视这些元素上的点击事件。我想确保任何给定的点击事件都来自用户操作,而不是页面上的 JS 创建和调度点击事件。有办法吗?

您正在寻找尚未实现的event.isTrusted

但是仍然可以检测点击事件是否是用户发起的。 chrome.permissions.request API requires a user gesture, or else it will report a failure. The chrome.permissions API cannot be used in content scripts (since Chrome 33). Fortunately, the user gesture state is preserved when you use the messaging API 从内容脚本和后台页面交换消息(自 Chrome 36)。因此,您可以使用以下逻辑来检测点击事件是否由用户生成并进行相应操作:

background.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message === 'is-user-gesture') {
        chrome.permissions.request({}, function() {
            // If an error occurred, then the message was not
            // initiated by a user gesture.
            var is_user = !chrome.runtime.lastError;
            sendResponse(is_user);
        });
        return true; // Async
    }
});

contentscript.js

function isUserEvent(callback) {
    chrome.runtime.sendMessage('is-user-gesture', function(is_user) {
        // Note: is_user could be undefined if the extension was reloaded
        // since the content script started.
        // We are conservative and assume that the action was not triggered
        // by a user gesture. Use "use is_user !== false" if you want to
        // assume that the action was triggered by the user if the extension
        // has reloaded.
        is_user = is_user === true;
        callback(is_user);
    });
}
document.body.onclick = function() {
     isUserEvent(function(is_user) {
         alert(is_user ? 'Triggered by user' : 'Spoofed event');
     });
};

要测试此方法,运行 在页面/内容脚本中执行以下步骤:

// Test fake event (will display "Spoofed event")
document.body.dispatchEvent(new CustomEvent('click'));
// TODO: Click on the body with your mouse (will display "Triggered by user")