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 badges2 Answers
Reset to default 9Yes: 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
版权声明:本文标题:javascript - getRangeAt() -- error if no text is selected - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741239064a2363604.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论