I'm developing an extension where i need to get the entire text content on the current tab. Now i've a plugin which retrieves selected text from the current tab. So, in essence i'm looking for the ctrl-A version of it :). This is what i've done so far taking the hint from @Derek.
This is in my event handler(this is just one, there are other listeners too for onUpdated
etc):
chrome.tabs.onSelectionChanged.addListener(function(tabId,changeInfo,tab){
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function (response) {
selectedtext = response.data;
});
chrome.tabs.sendRequest(tab.id, {method: "getText"}, function (response) {
alltext = response.data;
});
});
});
This is what i've written in the content script:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else if (request.method == "getText")
sendResponse({data: document.body.innerText});
else
sendResponse({});
});
However the document.body.innerText
is returning undefined. I need the entire text of the current tab in alltext
. Can someone help me out on this?
Thanks.
You can use
document.body.innerText
ordocument.all[0].innerText
to do it in the content script.It will get all the text content in the page, without any HTML code.
Or you can use
document.all[0].outerHTML
to get the HTML of the whole page.Example
In the Content Script
Added
So you want the content script to return the text to the popup. You can use:
chrome.tabs.getSelected
to get the tab selected,chrome.tabs.sendRequest
to send request to the content script,chrome.extension.onRequest.addListener
to listen to requests.Popup page
Content Script
This should work.
Use
executeScript
: (requires permissionactiveTab
)In case the
code
is complex, it's possible to define a function in the content script and call that function in thecode
(or usefile
).