Chrome扩展程序的内容脚本可以保证DOM事件是由用户启动的吗?

时间:2015-01-21 05:53:20

标签: javascript-events google-chrome-extension sandbox

我有一个扩展名,将HTML元素注入页面并观察这些元素上的点击事件。我想确保任何给定的click事件来自用户操作,而不是创建和分派click事件的页面上的JS。有没有办法这样做?

1 个答案:

答案 0 :(得分:2)

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

但仍然可以检测点击事件是否是用户启动的。 chrome.permissions.request API需要用户手势,否则会报告失败。 chrome.permissions API无法在内容脚本中使用(自Chrome 33起)。幸运的是,当您使用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")