I\'m having trouble with chrome extensions,. I have the permission \"tabs\" but I don\'t know how to retrieve the selected text on the page WITHOUT< a background page. &l
(Among several possible approaches) you can achieve what you want like this:
Below is the source code of a sample extension that does exactly that:
In maifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"browser_action": {
"default_title": "Test Extension",
"default_popup": "popup.html"
},
"permissions": [
"<all_urls>"
],
}
In popup.html:
<!DOCTYPE html>
<html>
<head>
<title>Google It!</title>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<input type="text" id="inp" size="20" placeholder="Search query..." />
<br />
<input type="button" id="btn" value="Google It!" />
</body>
</html>
In popup.js:
/* The URL for the Google search */
var google = 'http://google.com/#q=';
/* The function that finds and returns the selected text */
var funcToInject = function() {
var range = window.getSelection().getRangeAt(0);
var selectedText = range.cloneContents().textContent;
return selectedText;
};
/* This line converts the above function to string
* (and makes sure it will be called instantly) */
var jsCodeStr = ';(' + funcToInject + ')();';
window.addEventListener('DOMContentLoaded', function() {
/* Find our input elements from `popup.html` */
var inp = document.querySelector('input[type="text"]#inp');
var btn = document.querySelector('input[type="button"]#btn');
/* Open a new tab with the search results */
btn.addEventListener('click', function() {
var query = encodeURIComponent(inp.value);
chrome.tabs.create({ url: google + query });
});
/* Inject the code into all frames of the active tab */
chrome.tabs.executeScript({
code: jsCodeStr,
allFrames: true
}, function(selectedTextPerFrame) {
if (chrome.runtime.lastError) {
/* Report any error */
alert('ERROR:\n' + chrome.runtime.lastError.message);
} else if ((selectedTextPerFrame.length > 0)
&& (typeof(selectedTextPerFrame[0]) === 'string')) {
/* The results are as expected,
* populate the "search-query" input field */
inp.value = selectedTextPerFrame[0].trim();
}
});
});