最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.getSelection returning undefined or null - Stack Overflow

programmeradmin0浏览0评论

This is probably a very beginner question, but I'm about to pull my hair out because I can't figure out what I'm doing wrong. At this point, all I'm trying to do is get the selected text to print in an alert or the console (for testing). I've made sure .toString() method has been added to the returned Object from window.getSelection(). No matter what I do, the console and alerts display blank. Could anyone explain why?

I'm doing this in a local Chrome extension.

manifest.json

{
    "manifest_version": 2,
    "name":"Testing",
    "version": "0.1",
    "icons": {
       "48":"48.png"
    },

    "background": {
        "scripts": [ "background.js" ]
    },

    "permissions":[ "tabs" ],

    "browser_action": {
        "default_icon": { "19":"img19.png" }
    }
}

JavaScript

chrome.browserAction.onClicked.addListener(function(tab) {
    var selObj = window.getSelection();
    var selectionText = selObj.toString();
    alert(selectionText);       // displays a blank alert
    console.log(selectionText); // adds a blank line in the console
});

I'm learning. Thanks in advance.

This is probably a very beginner question, but I'm about to pull my hair out because I can't figure out what I'm doing wrong. At this point, all I'm trying to do is get the selected text to print in an alert or the console (for testing). I've made sure .toString() method has been added to the returned Object from window.getSelection(). No matter what I do, the console and alerts display blank. Could anyone explain why?

I'm doing this in a local Chrome extension.

manifest.json

{
    "manifest_version": 2,
    "name":"Testing",
    "version": "0.1",
    "icons": {
       "48":"48.png"
    },

    "background": {
        "scripts": [ "background.js" ]
    },

    "permissions":[ "tabs" ],

    "browser_action": {
        "default_icon": { "19":"img19.png" }
    }
}

JavaScript

chrome.browserAction.onClicked.addListener(function(tab) {
    var selObj = window.getSelection();
    var selectionText = selObj.toString();
    alert(selectionText);       // displays a blank alert
    console.log(selectionText); // adds a blank line in the console
});

I'm learning. Thanks in advance.

Share Improve this question asked Jan 26, 2014 at 4:14 BrianBrian 4,3642 gold badges30 silver badges59 bronze badges 4
  • you can do this window.getSelection().toString() to save some space, it works fine for me. You know when you click something it may cancel your selection. So when a selection is cancelled, the getselection should return empty string – Theofilos Mouratidis Commented Jan 26, 2014 at 4:53
  • After posting, I did some more searching and came across some similar questions which said DOM Elements can only be accessed by injecting a content.js script to run on the page you want access to. This one was helpful,so I'll try that and add an update. – Brian Commented Jan 26, 2014 at 4:55
  • @ΘεόφιλοςΜουρατίδης I tried that method as well, and it didn't print in the console or an alert (just for the sake of trying). I also tried using onmousedown, but I couldn't get that to work either. I'm working specifically in Chrome...would you verify again for me? – Brian Commented Jan 26, 2014 at 4:57
  • See this answer: stackoverflow./a/19100054/1507998 – rsanchez Commented Jan 26, 2014 at 12:00
Add a ment  | 

1 Answer 1

Reset to default 6

After researching on and off for the last 24 hours I finally have a working solution. Because I'm accessing a DOM Element, I needed to inject a content script and pass information back and forth from the background script. I also added the activeTab permission to my manifest.

manifest.json

{
    "manifest_version": 2,
    "name":"Simple Highlighter",
    "version": "1.0",
    "icons": {
        "19":"img19.png",
        "48":"48.png"
    },

    "content_scripts": [{                   
            // "matches": ["<all_urls>"],   only used for testing
            "js":["contentscript.js"]
        }],

     "background": {
        "scripts": [ "background.js" ]
    },

    "permissions":[ "tabs", "activeTab" ],

    "description": "Highlight web text and send it to a new Google Doc",

    "browser_action": {
        "default_icon": { "19":"img19.png" },
        "default_title":"Simple Highlighter"
    }
}

background.js

chrome.browserAction.onClicked.addListener(function() {                                                 
    chrome.tabs.query({active: true, windowId: chrome.windows.WINDOW_ID_CURRENT}, function(tabs) {      
        chrome.tabs.sendMessage(tabs[0].id, {method: "getSelection"}, function(response){               
            sendServiceRequest(response.data);                                                          
        });
    });
});

function sendServiceRequest(selectedText) {                                         
    var serviceCall = 'http://www.google./search?q=' + selectedText;
    chrome.tabs.create({url: serviceCall});
}

contentscript.js

chrome.runtime.onMessage.addListener( 
    function(request, sender, sendResponse) { 
        if (request.method == "getSelection") 
            sendResponse({data: window.getSelection().toString()});
        else
            sendResponse({});
    }
)

Obviously, this isn't doing what I originally set out to do...yet. But, I have it passing data, so I'll be working on the highlighting functionality next.

Reference Links

Chrome Extension get selected text

about sending messages among bg.html, popup.html and contentscript.js

发布评论

评论列表(0)

  1. 暂无评论