window.getSelection().toString() 在 Firefox 中不起作用(在 Chrome 中起作用)

dma*_*man 5 javascript firefox mozilla

当我在 Chrome 中突出显示数字时<input type="number">window.getSelection().toString()成功地给出了突出显示的文本。

但在 Firefox 中却并非如此。它总是空白的。有谁知道为什么?这确实令人困惑,因为MDN getSelection 文档指出它应该在 Firefox 57 中工作。

小智 4

这是一个火狐浏览器错误。请参阅https://bugzilla.mozilla.org/show_bug.cgi?id=85686

很旧了,还没修好。

我使用以下代码作为解决方法:

        function getSelectionText() {
            if (window.getSelection) {
                try {
                    var activeElement = document.activeElement;
                    if (activeElement && activeElement.value) {
                        // firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=85686
                        return activeElement.value.substring(activeElement.selectionStart, activeElement.selectionEnd);
                    } else {
                        return window.getSelection().toString();
                    }

                } catch (e) {
                }
            } else if (document.selection && document.selection.type != "Control") {
                // For IE
                return document.selection.createRange().text;
            }
        }        
Run Code Online (Sandbox Code Playgroud)