Get selected text and send to a web service/server in chrome extension. Communicate between content script and background page

1.Introduction  2.Prelims  3.Content Script  4.background.html  5.Server script  6.Download Extension  7.Comments


This tutorial explains the process of getting a text selection on mouse up(on text selection) and sending it to the web server using ajax.
Here we are going to detect whether the user had selected any text. For this window.getSelection is used. This function returns the selected text.
A text selection involves these actions. Mouse down, drag the mouse, the selected area is highlighted and release the mouse button. If there is any text selected then window.getselection returns that text else it will return an empty string.
So if the user had selected any text then the string length returned by window.getSelection will be greater than zero and with this condition we can detect that the user had selected a text. If the length is zero then it is not a text selection instead it would be any other mouse click event.


In this tutorial there is a manifest.json, background.html, a content script (myscript.js) and a dummy popup.html which does not do any process. First setting up the manifest.json.
When this extension is added or executed you can see a stick man icon near the wrench tool in chrome browser. Now the extension will wait for the user to select a text.
When the user selects a text and right clicks on it he can see an option in the context menu as "Send to server". When this option is clicked then the extension calls a function named savetext(present in background.html)
which will creates an ajax request and will send the selected text to the server.


  "name": "Word Reminder",
  "version": "1.0",
  "description": "Word Reminder.",
  "browser_action": {
    "default_icon": "images/stick-man1.gif",
  "background_page": "background.html",

  "content_scripts": [
		"matches": ["<all_urls>"],
      "js": ["js/myscript.js"]
  "permissions": [

Content Script

Here i have setup an event listener for mouse up.
In each mouse up event i am getting the value of selected text.
if the length is zero then the user did not select any text. he would have just did a click or double click.
If the length is greater than zero(non zero value) then the user had selected some text.
So at this point i am sending the selected text to the background.html page to be stored in the global variable (var seltext) of background.html
So later when i call a function to save the selected text in that function i will refer seltext to get the last selected text and i can call an ajax function which could send the selected text to the server.
The content script does not hold a global variable so i am sending it to the background.html where it can either be saved in memory or in disk(chrome.localstorage). I preferred to save it in memory and use it later.
I have defined a empty callback function in here which does nothing.
See the chrome extension documentation to see how sendRequest works. Here i send an object with message property (type of operation to do) and data property( the selected text). the callback function does nothing.
Next we will see what i have done in background.html
	var sel = window.getSelection().toString();
		chrome.extension.sendRequest({'message':'setText','data': sel},function(response){})


You can see the global variable seltext which will hold the selected text which will be posted by content script(myscript.js) to background.html
Next is the event listener for sendrequest action from content scripts.
When ever a send request is called like in the content script this event "chrome.extension.onRequest.addListener(function(request, sender, sendResponse" in the background.html will be fired.
So the line in content script chrome.extension.sendRequest({'message':'setText','data': sel},function(response){}) will cause this event to fire.
As a result i store the selected text in the global variale seltext.

The last 6 lines are executed when you open the browser. Which means when ever there is a selected text and a context menu this option "send to server" should be added.
And when ever the user clicks "send to server" option from the context menu the function savetext should be called.
And when that function is called i create an ajax request to send the selected text to the server.

So this background page adds a menu option in the context menu of a webpage when there is a text selection.
When that option is clicked the save text function is called. which will get the text from seltext variable and sends it to the server.
The variable seltext is copied with the selected text when ever the mouse is up with a text selection and as i had mentioned earlier this process is done by myscript.js


var seltext = null;

chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
		case 'setText':
			window.seltext =
			sendResponse({data: 'Invalid arguments'});

function savetext(info,tab)
	var jax = new XMLHttpRequest();"POST","http://localhost/text/");
	jax.onreadystatechange = function() { if(jax.readyState==4) { alert(jax.responseText);	}}

var contexts = ["selection"];
for (var i = 0; i < contexts.length; i++)
	var context = contexts[i];
	chrome.contextMenus.create({"title": "Send to Server", "contexts":[context], "onclick": savetext});  


Server script

This script is totally straight forward. I have setup the field word to be unique and the table name as words and the database name some thing like wori.


		@mysql_connect('localhost','root','') or die(mysql_error());
		$word = trim($_POST['text']);		
		if(empty($word))die('Empty String');
		$word = addslashes(stripslashes($word));
		$query = "insert into words set word='$word'";

		mysql_query($query) or die(mysql_error());
		die('Updated Successfully');

Download Source Code

The zip file contains the manifest.json, background.html, contentscript (myscript.js) and other files.
Click here to download the chrome extension for getting the selected text and sending it to the web server

That is all folks. Enjoy.

By -

Comments, Suggestions, Objections, ...