Show selected text on page in extension popup.

3,931 views
Skip to first unread message

dvh

unread,
Feb 25, 2011, 3:55:31 PM2/25/11
to Chromium-extensions
I have basic hello world extension. I want to show in alert box what
text on page is selected. I have this code in popup page:

<script>
alert("Selected Text is : " + window.getSelection().toString());
</script>

But it write: "Selected Text is : " like there is no selected text.
Perhaps because "window" is the popup page itself. How to get to the
page in active, current tab? What I actually want is (in pseudocode):

alert(chrome.activeTab.window.getSelection().toString);

Thanks.

Arne Roomann-Kurrik

unread,
Feb 28, 2011, 6:35:02 PM2/28/11
to dvh, Chromium-extensions
Your intuition is correct, the window object refers to the popup, not the current web page.

Use chrome.tabs.getSelected: http://code.google.com/chrome/extensions/tabs.html#method-getSelected with a null argument for window to get the ID of the currently visible tab.  Then you can call chrome.tabs.executeScript to run your snippet in the context of the tab itself: http://code.google.com/chrome/extensions/tabs.html#method-executeScript

Of course, you'll need to use message passing to pass the selected text back to the popup page.  

This is a bit convoluted, luckily I have written a sample which does more or less this: https://github.com/kurrik/chrome-extensions/tree/master/contentscript-selection

Hope that helps,
~Arne


--
You received this message because you are subscribed to the Google Groups "Chromium-extensions" group.
To post to this group, send email to chromium-...@chromium.org.
To unsubscribe from this group, send email to chromium-extens...@chromium.org.
For more options, visit this group at http://groups.google.com/a/chromium.org/group/chromium-extensions/?hl=en.


Reply all
Reply to author
Forward
0 new messages