开发者

Get the selected text of a web page in google chrome extension

开发者 https://www.devze.com 2023-01-03 20:16 出处:网络
I am developing a Google Chrome extension. When a popup is clicked, 开发者_高级运维I would like the input box present in the popup.html file to contain the selected text of the current webpage.

I am developing a Google Chrome extension. When a popup is clicked, 开发者_高级运维I would like the input box present in the popup.html file to contain the selected text of the current webpage.

Example textbox:

<input id="searchBox" type="text" />

When text is selected in a webpage, the textbox should contain the selected word. I tried with chrome.extension.getBackgroundPage().getSelection() but it is not working.


There was a thread about this on google groups: how to get HTML code from selection?

var selection = window.getSelection(); 
var range = selection.getRangeAt(0); 
if (range) { 
  var div = document.createElement('div'); 
  div.appendChild(range.cloneContents()); 
  alert(div.innerHTML); 
}

You can use this in the console or in a plugin, either way.


What youre trying to do requires quite a bit of coding because of Chrome's extreme security precautions.

chrome.extension.getBackgroundPage().getSelection() will not work because the "BackgroundPage" is not the current webpage. You need something like:

chrome.tabs.executeScript(null, {code:"alert(window.getSelection().toString());"})
//alerts the selected text

However, to transfer that text back to the popup is a long and migraine-causing process. Read Contentscripts and Extension Messaging if youre up for the challenge.


here is another simple solution to get the selected the text in the form of string, you can use this string easily to append a div element child into your code:

              var text = '';
              if(window.getSelection){
                text = window.getSelection();
              }else if(document.getSelection){
                text = document.getSelection();
              }else if(document.selection){
                text = document.selection.createRange().text;
              }
              text=text.toString();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号