chrome 扩展:如何将“keydown"事件发送到页面的输入? [英] chrome extension: how to send 'keydown' event to page's input?

查看:41
本文介绍了chrome 扩展:如何将“keydown"事件发送到页面的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试网页,如果我在它的输入字段中按下一个键,它就会发出警报:

I have a test web page that alerts if i hit a key in it's input field:

<!doctype html>
<html>
<head>
  <script type="text/javascript" src="jquery-1.9.1.min.js"></script>
  <script>
    $( document ).ready( function() {
      $( '#foo' ).keydown( function() { alert( "debug" ); } );
    });
  </script>
</head>
<body>
  <input id='foo' type='type'/>
</body>
</html>

我有这个 chrome 扩展,可以修改输入文本并触发 keydown 事件:

And i have this chrome extension that modifies input text and fires keydown event:

$( document ).ready( function() {
  window.setTimeout( function() {
    $( '#foo' ).val( "foo" );
    $( '#foo' ).keydown();
  }, 2000 );
});

如果我安装扩展,2 秒后(如预期)文本被修改 - 但不显示警报,所以我可以建议 keydown 事件不会从扩展沙箱传递到页面 javascript 处理程序.是否可以以某种方式修改我的代码,以便扩展程序可以模拟页面上的 javascript 可以看到的 keydown?我正在通过 chrome 扩展程序自动化第三方网站,其中一个输入需要 keyup 来检测值更改(我正在自动化的页面写得不好 - 但我没有任何控制其他是源代码).

If i install extension, after 2 seconds (as expected) text is modified - but alert is not displayed, so i can suggest that keydown event is not passed from extension sandbox into page javascript handler. Is it possible to modify my code somehow so extension can emulate keydown that javascript on the page can see? I'm automating a third-party website via chrome extension, and one of the inputs requires keyup to detect value change (the page i'm automating is written badly - but i don't have any control other it's source code).

推荐答案

您的代码无法正常工作,因为 jQuery 的 keydown() 方法实际上并未触发真正的"keydown 事件.相反,jQuery 在 jQuery.cache 中查找绑定"事件处理程序,并调用相应的函数.

Your code is not working because jQuery's keydown() method does not actually trigger a "real" keydown event. Instead, jQuery looks up the "bound" event handlers in jQuery.cache, and calls the corresponding functions.

由于您的内容脚本的 jQuery 对象与页面的 jQuery 对象不同,因此调用 .keydown() 不会导致任何操作.

Since your content script's jQuery object differs from the page's jQuery object, invoking .keydown() doesn't cause any action.

在您的情况下,我建议在页面中注入您的代码,以便您的代码在与页.然后,调用 $('#foo').keydown() 将使用页面的 jQuery 对象,并导致预期的行为.

In your case, I suggest to inject your code in the page, so that your code runs in the same context as the page. Then, calling $('#foo').keydown() will use the page's jQuery object, and result in the expected behaviour.

不依赖于任何库的通用解决方案是使用 KeyboardEvent 构造函数 (DOM4 中定义) 来触发事件:

A general solution, which doesn't depend on any library is to use the KeyboardEvent constructor (defined in DOM4) to trigger the event:

var event = new KeyboardEvent('keydown');
document.querySelector('#foo').dispatchEvent(event);

这篇关于chrome 扩展:如何将“keydown"事件发送到页面的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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