window.getSelection().toString() not working in Firefox (works in Chrome)

那年仲夏 提交于 2020-07-08 13:54:00

问题


When I highlight numbers on an <input type="number"> in Chrome, window.getSelection().toString() successfully gives me the highlighted text.

But this is not so in Firefox; it is always blank. Does anyone know why? This is really confusing since MDN getSelection documentation states it should work in Firefox 57.


回答1:


This is a firefox bug. See https://bugzilla.mozilla.org/show_bug.cgi?id=85686

Very old one, not fixed yet.

I use the following code as workaround:

        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;
            }
        }        


来源:https://stackoverflow.com/questions/47517432/window-getselection-tostring-not-working-in-firefox-works-in-chrome

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