admin管理员组

文章数量:1279176

I use this simple Javascript code to retrieve text that was selected on a webpage:

var userselection = window.getSelection(); //user selection will be a Selection-Object
var rangeObject = userselection.getRangeAt(0); 

The code works fine if text is selected. If I just click in the text that could be selected I get a range object too, it is collapsed as expected.

But if I don't select nor click, Firefox throws this error:

uncaught exception: [Exception... "Component returned failure code: 0x80070057
(NS_ERROR_ILLEGAL_VALUE)  [nsISelection.getRangeAt]" nsresult: "0x80070057 
(NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: file:///home/jan/Webprojekte/test-range
selection.html# :: who :: line 16" data: no]

Is there a clean way to prevent the error but still notificate the user that no text was selected?

I use this simple Javascript code to retrieve text that was selected on a webpage:

var userselection = window.getSelection(); //user selection will be a Selection-Object
var rangeObject = userselection.getRangeAt(0); 

The code works fine if text is selected. If I just click in the text that could be selected I get a range object too, it is collapsed as expected.

But if I don't select nor click, Firefox throws this error:

uncaught exception: [Exception... "Component returned failure code: 0x80070057
(NS_ERROR_ILLEGAL_VALUE)  [nsISelection.getRangeAt]" nsresult: "0x80070057 
(NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: file:///home/jan/Webprojekte/test-range
selection.html# :: who :: line 16" data: no]

Is there a clean way to prevent the error but still notificate the user that no text was selected?

Share Improve this question edited Jul 9, 2010 at 11:43 gblazex 50.1k12 gold badges99 silver badges92 bronze badges asked Jul 9, 2010 at 11:22 JanDJanD 7,4603 gold badges25 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Yes: check the selection's rangeCount property first. If it's zero, don't call getRangeAt().

i got the same problem. but in my case i had rangeCount equals 1. accidentaly i've found this way to solve the problem

you need to set timeout function and then everything goes well

setTimeout(function(){
    var userselection = window.getSelection(); //user selection will be a Selection-Object
    var rangeObject = userselection.getRangeAt(0);
},100)

本文标签: javascriptgetRangeAt()error if no text is selectedStack Overflow