如何在Greasemonkey脚本中模拟按键? [英] How to simulate a keypress in a Greasemonkey script?

查看:96
本文介绍了如何在Greasemonkey脚本中模拟按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在线上找到了很多有关如何使用initEvent

I have found lots of info online about how to use the initEvent and dispatchEvent functions, but I can't for the life of me get them to work in practice.

我正在尝试获取一个脚本,以每5秒按一次 Enter 键.我的用户脚本代码(减去无关的元数据)如下:

I'm trying to get a script to press the Enter key every 5 seconds. My userscript code (minus irrelevant metadata) is below:

// ==UserScript==
// @namespace      http://userscripts.org/scripts/show/153134
// @require        https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js
//
// @grant          unsafeWindow
//
// ==/UserScript==

$(function(){
window.setInterval(function(){
    var ev = document.createEvent("KeyboardEvent");
    ev.initKeyEvent("keypress", true, false, window, 0, 0, 0, 0, 13, 13);
        window.dispatchEvent(evt);
}, 5000);
});

在userscript上签出我的脚本,以查看其运行情况(添加用户include域并在任何<textarea>上对其进行测试).是Greasemonkey只是不允许它通过,还是我需要做一些不同的事情?

Checkout my script on userscript to see how poorly it works (add a user include domain and test it on any <textarea>). Is Greasemonkey just not letting it through, or do I need to do something differently?

推荐答案

该代码中存在复制粘贴错误.
不要使用window.dispatchEvent(evt);;
使用window.dispatchEvent(ev);

There is a copy-paste error in that code.
Don't use window.dispatchEvent(evt);;
use window.dispatchEvent(ev);

将事件发送到window可能也不是您所需要的. (或者可能是.链接到目标页面.)

Sending the event to window may not be what you need either. (Or it could be. Link to the target page.)

也许将事件发送到文档:

Maybe send the event to the document:

document.body.dispatchEvent(ev);

或将其发送到特定节点:

Or send it to a specific node:

var targetNode  = document.querySelector ("#content textarea"); // Etc.
targetNode.dispatchEvent (ev);


或者,因为您使用的是jQuery:


Or, since you are using jQuery:

var ev = $.Event('keypress');
ev.which = 13; // Carriage-return (Enter)
$('body').trigger(ev);

这篇关于如何在Greasemonkey脚本中模拟按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆