How do you configure Firefox to allow Javascript to intercept a value pasted from the clipboard?

狂风中的少年 提交于 2019-12-02 23:14:46

In short, I don't think it's possible to do what you want to do how you want to do it. Mozilla (and most modern browsers) limit clipboard access for security reasons. That you seem to have easily gotten around this restriction in IE is not a comforting thought.

That being said, plugins have different restrictions than web pages, and you may be able to get around this limitation by writing one (or maybe even leveraging flash). Even with a plugin, though, I suspect that the only way for you to block someone from pasting something into a web form (or whatever) would be to preemptively scrub their clipboard.

If all you want to do is prevent certain strings from being entered into a text box, you're best bet is to monitor events on the text box itself.

If I'm reading you right, though, it sounds like you want to force your users to type (and only type) something into a form, and I can't think of a trivial way of doing this. A couple non-trivial options:

  1. Set the textbox to readonly, and pop-up a virtual keyboard to force the user to "type" into the box using their mouse. (You'd have to build the keyboard yourself out of HTML and JavaScript, or find a suitable solution somewhere.)
  2. Monitor the oninput event; if the textbox changes more quickly then what a person could reasonably be expected to type, reject the changes.

Neither of those are exactly pretty, but if you want to create solutions using open web technologies, then you have to accept the limitations of the system you're building on top of, as well as its benefits.

Grubby but crossbrowser way is to compare value of current input with previous on onchange event.

If it's length increased or value differs too much (not only reduсed but have a lot of new chars) -- probably something is pasted from clipboard. Something like this:

$('input, textarea').change(function(){
  var prev = $(this).data('prev-val'), 
      current = $(this).val();
  if (is_big_changes(prev,current)) {
    $(this).val(my_filter_func(current));
  }
  if (!prev) {
     $(this).data('prev-val', current);
  } 
})

(it's only proof of concept, so I used jQuery to avoid a lot of coding)

Where is_big_changes and my_filter_func -- functions you need to implement.

Warning A lot of evil bugs is potentially possible with this approach and I know, it looks extremely ugly. My deal is to propound.

Can we say, what you alternative want is detecting a clipboard paste? Since when you know what was before in there, you know what has been changed.

So why not simply hook onchange? All character identical from beginning and end of the content are not pasted. If you want to differ this from simple keystrokes, listen to keydown/keypress as well, then you know, which changes come from "elsewhere".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!