【发布时间】:2012-09-19 18:55:33
【问题描述】:
首先让我说有问题的代码是UserScript 的一部分,因此,正常的 DOM 规则和 Javascript 方法不起作用。
情况如下:
我编写了一个与在线聊天网站交互的用户脚本。我有许多在用户脚本中生成的button。其中一些按钮位于表单内部,而许多按钮则不在。
通过 GreaseMonkey 添加的元素存在于两个世界中——它们存在于页面 DOM 中,它们存在于稍高的 UserScript 世界中,这意味着这些行:
event.preventDefault = true;
event.stopPropagation = true;
阻止UserScript 的其余操作运行,但不会阻止按钮导致表单提交。
作为一种解决方法,我正在构建 span 元素而不是 button。这行得通,但它确实破坏了聊天室的视觉布局。
有谁知道防止UserScripts 添加的元素以防止form 提交的方法?如果做不到这一点,我会梦想有人知道如何让span 看起来像本地人button。
编辑:我有一个似乎可以工作的解决方案——但我还没有在每个 UserScript 环境下对其进行全面测试:
// Yes, yes, poorly named but it was a SPAN
// userWindow is an alias for unsafeWindow.
// (Used to run under a userScript environment for IE and I had to emulate a lot)
var span = document.createElement("input");
span.value = text;
span.type = "button";
span.className = "cpbutton";
// Add it to the body just long enough to set up a page-level, DOM0 event handler
var body = userWindow.document.getElementsByTagName("body")[0];
var tname = "IAmTheVeryModelOfAModernMajorGeneral";
span.id = tname;
body.appendChild(span);
userWindow.document.getElementById(tname).onclick = function() {return false;};
body.removeChild(span);
span.id = "";
【问题讨论】:
-
to prevent elements added by UserScripts to prevent form submissions。这是否意味着您要阻止或允许提交表单? -
我想阻止表单提交。
-
@Brock -- 是的.. "TamperMonkey" -- 或者更具体地说,TamperMonkey Beta。嘘,我的校对通常比这更好。 (我有阅读障碍。)
-
没问题,只是想澄清一下。
-
只是为了让您知道,
unsafeWindow.document.getElementById(tname).onclick = function() {return false;};阻止了我的表单提交
标签: event-handling dom-events greasemonkey tampermonkey userscripts