网站上启用“粘贴”功能的脚本

15

问题涉及特定网站:NS.nl上的票务订单。在该页面中,有一个文本输入框用于输入电子邮件,但是该字段已禁用Ctrl-V(粘贴)。

问题:什么Greasemonkey脚本将启用该字段的粘贴功能?

我已经研究了各种解决方案,包括:

并得出以下脚本,但(不幸的是)它不能在给定的网站上工作(使用FF v40,Greasemonkey v3.4进行测试):

// Taken from http://userscripts-mirror.org/scripts/review/40760
unsafeWindow.disable_paste = function() { return true; };

// jQuery is already available on the page:
var $j = jQuery.noConflict();

// Site generates the form on-the-fly, so we schedule the necessary modifications for later:
setTimeout(function() {
    $j(document).off('copy paste', '[data-regex=email], [data-regex=emailRepeat]');
    $j(document).off('keyup keydown keypress cut copy paste');

    // Taken from https://stackoverflow.com/questions/28266689/how-to-enable-paste-on-html-page-with-locked-cmdv
    $j('*').each(function(){                                                
        $j(this).unbind('paste');
    });
}, 2000);

由于该网站动态构建表单,因此使用延迟执行(通过setTimeout())。下图显示了“有问题”的元素:

禁止粘贴的表单字段元素

2个回答

24

选中的答案对我没有用。我发现这个简单的脚本确实起作用:

document.addEventListener('paste', function(e) {
  e.stopImmediatePropagation();
  return true;
}, true);

这里发现了一个方法:https://www.howtogeek.com/251807/how-to-enable-pasting-text-on-sites-that-block-it/

注:对于一些网站,可能还需要停止keydown的传播。

document.addEventListener('keydown', function(e) {
  e.stopImmediatePropagation();
  return true;
}, true);

5
  • To unbind the events you should provide the original handler set by the page:

    // ==UserScript==
    // @name         Re-enable copy/paste of emails
    // @include      https://www.ns.nl/producten/s/railrunner*
    // @grant        none
    // ==/UserScript==
    
    $(function() {
        $(document).off("copy paste",
                        "[data-regex=email], [data-regex=emailRepeat]", 
                        $._data(document, "events").paste[0].handler);
    });
    
  • Another method that turned out to work only in Chrome is to assign a direct event listener for oncopy/onpaste element properties, thus it'll have a higher priority than the site's listeners attached to the document. In your listener prevent other listeners from seeing the event via stopImmediatePropagation:

    var input = document.querySelector("[data-regex=email], [data-regex=emailRepeat]");
    input.onpaste = input.oncopy = function(event) { event.stopImmediatePropagation() };
    

太好了!我想我在某个地方看到过这个解决方案,但肯定搞砸了事情。我注意到只有在从setTimeout()调用脚本时才能正常工作(也就是说,如果按照您提供的文字逐字理解,它不起作用,至少在FF中是这样)。我尝试使用$(document).on('copy paste', '[data-regex=email], [data-regex=emailRepeat]', function(event) { event.stopImmediatePropagation(); });但那并不起作用。有什么想法吗? - dma_k
请查看更新后的答案。请注意,不必使用计时器,只需将代码包装在 $(function() { ....... }); 中即可,这样它将在文档和jQuery都加载完成后执行。 - wOxxOm
不幸的是,对我来说,包装成 $(function() { }) 不起作用。它对你有用吗?实际上,我不明白为什么它应该起作用,因为 $(document).on('events', 'selector', function) 也会在给定节点附加到 DOM 后触发(所以我认为它是更好的候选者,可以正常工作)。 - dma_k
是的,它在FF42+Greasemonkey3.5和Chrome+Tampermonkey上对我有效。你尝试过我发布的确切用户脚本了吗?还是你修改了什么东西? - wOxxOm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接