I am running this piece of code, for de-selecting a word a user selected in an iframe, when he selects another word outside the iframe:
function getCurrentWord() {
var range;
var w = "";
if (document.selection) {
////IE
range = document.selection.createRange();
w = trim(range.text);
} else {
////NOTIE
w = trim(window.getSelection().toString());
}
if (w != "" && document.getElementById("frmBook")) {
var oTextRange;
if (document.selection) {
////IE
oTextRange = document.getElementById("frmBook").contentWindow.document.selection.createRange();
oTextRange.expand("word");
oTextRange.execCommand("unselect") ;
} else {
////NOTIE
oTextRange = document.getElementById("frmBook").contentWindow.getSelection();
oTextRange.collapseToStart();
}
}
if (w == "" && document.getElementById("frmBook")) {
if (document.selection) {
////IE
range = document.getElementById("frmBook").contentWindow.document.selection.createRange();
w = trim(range.text);
} else {
////NOTIE
w = trim(document.getElementById("frmBook").contentWindow.getSelection().toString());
/*
IF I PUT IT HERE IT DOESN'T SHOW AN ERROR
oTextRange = document.getElementById("frmBook").contentWindow.getSelection();
oTextRange.collapseToStart();
*/
}
}
return w;
}
The problem is i get this error on firefox error console:
Timestamp: 9/5/2012 12:20:42 μμ
Error: uncaught exception: [Exception… “An attempt was made to use an object that is not, or is no longer, usable” code: “11” nsresult: “0x8053000b (NS_ERROR_DOM_INVALID_STATE_ERR)” location: “http://192.168.0.88/test.js Line: 295″]
and that error occurs when the code is at the
oTextRange.collapseToStart();
line.
I tried to run it in a single line like this :
document.getElementById("frmBook").contentWindow.getSelection().collapseToStart();
but i get the same error
frmBook is the ID of the iframe
IF i run that piece of code which causes the error where I have commented it out, it doesn’t show an error and that’s weird!
Anybody knows what am I doing wrong ?
Thanks in advance
Looking at (what may possibly be an old version of) the source code at http://dxr.lanedo.com/mozilla-central/layout/generic/nsSelection.cpp.html it seems that
collapseToStartwill produce that error if nothing is actually selected. You could check whetheroTextRange.rangeCountis < 1, and simply not do the collapse if so. (If there’s some reason why that should be impossible, then you probably have a different problem.)