PDA

View Full Version : problem with document.selection


---dom---
03-23-2006, 02:21 PM
HI,


Wat I'm tryin to do is read in some text using:

function getSelectedText() {
if (document.selection) {
var range = document.selection.createRange();
document.body.createTextRange();
var str =range.text.toString()

return str;
}
}

then add str to the search string for google using:

function googleSearch()
{
var target='http://www.google.com/search?q=';
var str = getSelectedText();
self.name = "body";
msgWindow = window.open(target + str);
}


and finally call it through a context menu.

However the google search returns [object] or nothing.


Any ideas???

artman 186
03-23-2006, 08:28 PM
First off, you don't need this:

document.body.createTextRange();

Secondly, your script seemed to work just fine for me:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Untitled</title>

<script type="text/javascript">

function getSelectedText() {
if (document.selection) {
var range = document.selection.createRange();
var str = range.text;

return str;
}
}

function googleSearch()
{
var target='http://www.google.com/search?q=';

var str = getSelectedText();
alert(str);
self.name = "body";
msgWindow = window.open(target + str);
}
</script>
</head>

<body>

Moo<p>

<input type="button" onclick="googleSearch()" value="Search">

</body>
</html>

Highlight 'Moo' and it works just fine. I took "toString()" off because you don't need it, but it shouldn't hurt anything.

This script won't work in FireFox, although I assume you know that based on the snippet you posted.

For some information on a cross-browser version of leveraging selected text, check this out:

http://www.quirksmode.org/js/selected.html

---dom---
03-23-2006, 11:46 PM
Thanks:thumbsup:
I see where i was messin up.


Is there anyway that instead of placing a button on the page, I could select the text through clicking on my context menu?