I'm working on a chrome extension which copies the selected/highlighted text into a textarea. This is what I used so far:
chrome.tabs.executeScript( {
code: "window.getSelection().toString();",
}, function(selection) {
document.getElementById("output").value = selection[0];
});
But now I've switched from the popup.html to a window which I created like this
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({
url: chrome.runtime.getURL("window.html"),
type: "panel", height: 590, width:850, focused: false
}, function(win) {
});
});
And I can't get the selected text into this window anymore. I also copied the current URL of the activetab doing like so:
chrome.tabs.getSelected(windowId, function(tab) {
document.getElementById('url').innerHTML = tab.url;
var windowId = tab.id
});
and I could make this work for the new window using:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
document.getElementById('url').innerHTML = tabs[0].url;
});
So my question is: How can I get the selected/highlighted text into the textarea inside my newly created window? Is there something similiar to the
chrome.tabs.query()
just for highlighted text?
Use executeScript's tabId parameter to inject in the clicked tab, then pass the text using any of these:
'window.html?url=' + encodeURIComponent(text)
Here's an example for localStorage.
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
getSelectedText(tab.id, function(text) {
localStorage.selectedText = text;
chrome.windows.create({
url: "/window.html",
type: "panel", height: 590, width:850, focused: false
});
});
});
function getSelectedText(tabId, cb) {
chrome.tabs.executeScript(tabId, {
code: "window.getSelection().toString();",
}, function(selection) {
cb(selection[0]);
});
}
window.html:
.................
<script src="window.js"></script>
</body>
</html>
window.js:
document.getElementById('url').textContent = localStorage.selectedText || '';
delete localStorage.selectedText;