处理Firefox扩展中的文本选择事件(阻止用户选择文本)

时间:2011-03-06 15:36:15

标签: javascript firefox javascript-events firefox-addon textselection

我想知道在chrome代码中我们是否有更好的方法来检测用户何时选择/突出显示当前页面中的某些内容而不是监听keyup / mouseup并检查window.getSelection()。有什么想法吗?

编辑:实际上,我正在尝试做的只是阻止用户在contentDocument中选择任何文本。完成这一切的东西也会很好。 (获得选择活动背后的想法只是preventDefault()或其他getSelection().removeAllRanges()

edit2:请注意,我不仅要阻止突出显示,而且还要防止选择发生。

edit3:我不需要阻止复制,而是选择元素。

5 个答案:

答案 0 :(得分:4)

如果您将以下scipt放入正文中,则会在Firefox中禁用选择:

<script type="text/javascript">
   document.body.style.MozUserSelect = "none";
   document.body.style.cursor = "default";
</script>

它不仅禁用突出显示,还禁用选择本身。如果您尝试通过鼠标或箭头键选择区域(在按下SHIFT时单击位置并使用箭头键导航)并按STRG+C,则不会发生任何事情。

此更改后唯一有效的选项是STRG+A(没有选择可见,但STRG+A&amp; STRG+C复制全部。可以通过键盘事件来避免这种情况。


编辑:我看到你评论了Mozilla Doc Center的链接,虽然他们写的只控制了外观,我在Firefox 3.6中的所有测试都表明它也会影响选择,而不仅仅是外观。但它可能会在未来的版本中改变......

答案 1 :(得分:2)

如果没有合适的事件,例如selectselectstart(在Firefox中确实不存在select事件,但仅将其应用于表格控件),所有你可以做的是使用鼠标和键盘事件,如问题中所建议的那样。防止文档中所有mousedown事件的默认操作是不好的,因为它会阻止所有交互式元素(如链接和表单元素)起作用。相反,您可以执行以下操作,使用鼠标和键盘对选区进行切换。

它不会阻止在上下文和编辑菜单中通过“全选”进行选择,因为在Firefox中根本无法检测到这些选项。如果你需要处理这个问题,那么轮询选择是你唯一的希望。

function killSelection() {
    window.getSelection().removeAllRanges();
}

document.addEventListener("mousedown", function(evt) {
    document.addEventListener("mousemove", killSelection, false);
}, false);

document.addEventListener("mouseup", function(evt) {
    document.removeEventListener("mousemove", killSelection, false);
}, false);

document.addEventListener("keydown", killSelection, false);

window.addEventListener("blur", function(evt) {
    document.removeEventListener("mousemove", killSelection, false);
}, false);

答案 2 :(得分:2)

您可以使用css

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

答案 3 :(得分:1)

您可以使用CSS来阻止用户选择文本。请在此处查看我的回答:How to disable text selection highlighting using CSS?

要在Firefox中通过JavaScript设置此项,您可以执行以下操作:

document.body.style.MozUserSelect = "-moz-none";

答案 4 :(得分:1)

复制命令由事件启用和禁用。您可以通过创建命令更新程序来获得此事件的通知。

<commandset commandupdater="true" events="select"
            oncommandupdate="setTimeout(selectNone, 0);"/>