Prevent JavaScript window.getSelection() circular reference

别来无恙 提交于 2019-12-31 03:57:26

问题


See this demo (dependent on selectionchange event which works in Chrome only at this moment): http://jsfiddle.net/fyG3H/

Select some lorem ipsum text and then focus the text input. In the console log you will see that there is a DOMSelection object. It has an anchorNode value of HTMLBodyElement while it should have one of Text.

I didn't know why this was happening until I tried stringfying the selection object: http://jsfiddle.net/fyG3H/1/

This gives the following error:

Uncaught TypeError: Converting circular structure to JSON

Do you know how I can prevent this circular reference caused by window.getSelection() ?

EDIT

New demo which works in other browsers too but still gives the wrong anchorNode: http://jsfiddle.net/fyG3H/5/

And with JSON.stringify: http://jsfiddle.net/fyG3H/6/

Firefox seem to return an empty {} instead of throwing an error.


回答1:


You need to invoke toString() on getSelection(). I've updated your fiddle to behave as you'd expect.

var selection;

$('p').bind('mouseup', function() {
    selection = window.getSelection().toString();
});

$('input').bind('focus', function() {
   this.value = selection;
   console.log(selection); 
});

See demo


EDIT:

The reason that you're not getting the correct anchor node is that the DOMSelection object is passed by reference and when you focus on the input, the selection gets cleared, thus returning the selection defaults corresponding to no selection. One way you can get around this is to clone the DOMSelection properties to an object and reference that. You won't have the prototypal DOMSelection methods any more, but depending on what you want to do this may be sufficient.

var selection, clone;

$('p').bind('mouseup', function() {
    selection = window.getSelection();
    clone = {};
    for (var p in selection) {
        if (selection.hasOwnProperty(p)) {
            clone[p] = selection[p];
        }
    }
});

$('input').bind('focus', function() {
   console.dir(clone); 
});

See demo



来源:https://stackoverflow.com/questions/6880516/prevent-javascript-window-getselection-circular-reference

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