Douglas Quaid
Douglas Quaid

Reputation: 1

Replacing user selected text in Javascript

Been googling this for a while and it seems really simple, but I can't work out the issue. I have a chrome extension where when you select some text, you right click and there is a button which will perform some maths on the selection. But for some reason, I can't get the selection to appear in an alert window.

if (window.getSelection) 
{
    window.alert("Does it enter if window.getselection");
    sel=window.getSelection();
    window.alert(sel);
}

So it enters the if statement, displays the first alert, then the second alert is blank. Losing my mind trying to work this out, it feels like it's going to be something so simple that I've missed. Also, what would be the best method of replacing the selected text? Thanks.

EDIT: You guys wanted to see my Manifest file.

{
"name": "Convert",
"description": "lorem",
"version": "0.6",
"permissions": ["contextMenus", "tabs", "windows"],
"background": {
"scripts": ["conversion.js"]
},
"manifest_version": 2
}

I'm guessing I've done something wrong here, I am a greenhorn when it comes to Chrome Extnesions.

Upvotes: 0

Views: 95

Answers (2)

Xan
Xan

Reputation: 77531

You are a beginner at Chrome Extensions; therefore, take a look at the Architecture Overview.

If you read it, you will come back enlightened that background code runs in a separate page, and window refers to it and not the currently open and visible tab. To access that, you normally need some form of a Content Script.

But before you start implementing the content script, let's have another look at the context menu API.

The handler of a context menu click event receives an info object that, among other things, contains selectionText with the text selected at the moment of the invocation of the context menu. If that is all you want (and not the full Selection object), you don't need to interact with the page at all:

function handleContext(info){
  if(info.selectionText) {
    // There was something selected, do stuff with it
  }
}

If you DO need the full selection object, here's the minimal code for it (requires activeTab permission):

function handleContext(info, tab){
  if(tab){
    chrome.tabs.executeScript(
      tab.id,
      {code : "window.getSelection();"},
      function(results) {
        // Do something with results[0]
      }
    );
  }
}

See Programmatic Injection and executeScript docs for reference.

Upvotes: 2

cmousset
cmousset

Reputation: 795

You forgot the parenthesis. Try

if (window.getSelection()) 
{
    window.alert("Does it enter if window.getselection");
    sel=window.getSelection();
    window.alert(sel);
}

Because the function getSelection exists, window.getSelection is true, regardless of what window.getSelection() returns.

Upvotes: -1

Related Questions