简体   繁体   中英

Prevent JavaScript window.getSelection() circular reference

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM