Chrome Extension - Get entire text content of the current tab - html

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 or document.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
function getText(){
return document.body.innerText
}
function getHTML(){
return document.body.outerHTML
}
console.log(getText()); //Gives you all the text on the page
console.log(getHTML()); //Gives you the whole HTML of the page
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,
and chrome.extension.onRequest.addListener to listen to requests.
Popup page
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getText"}, function(response) {
if(response.method=="getText"){
alltext = response.data;
}
});
});
Content Script
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if(request.method == "getText"){
sendResponse({data: document.all[0].innerText, method: "getText"}); //same as innerText
}
}
);
This should work.

Use executeScript: (requires permission activeTab)
chrome.tabs.executeScript(null, {
code: `document.all[0].innerText`,
allFrames: false, // this is the default
runAt: 'document_start', // default is document_idle. See https://stackoverflow.com/q/42509273 for more details.
}, function(results) {
// results.length must be 1
var result = results[0];
process_result(result);
});
In case the code is complex, it's possible to define a function in the content script and call that function in the code (or use file).

Related

Chrome extension create new tab and send message from popup.js to content script of new tab

I am developing a chrome extension where my popup.js receives a message from a content script on the current page and creates an array. Then on a button press, popup.js creates a new tab (which has a content script running) and sends that content script a message containing the array.
My popup.js:
//this message is sent from a different content script (for current page), not shown here
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action === "getSource") {
var arr = JSON.parse(request.source);
//create new tab
chrome.tabs.create({url: "newtab.html"}, function(tab){
//send message to new tab
chrome.tabs.sendMessage(tab.id{
action: "getDataArray",
source: JSON.stringify(arr)
});
}
});
newtab-contentscript.js:
$(document).ready( function() {
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action === "getDataArray") {
$("#result").html(JSON.parse(request.source));
}
});
newtab.html:
<script src="newtab-contentscript.js"></script>
Problem: The newtab-contentscript.js never seems to receive the message.
Are the any mistakes with how I am creating a tab or sending the message. Do you have any suggestions to how to fix this issue?
As we discussed in the comments, I guess maybe $(document).ready is too late to receive messages from chrome.tabs.sendMessage, you can test it by comparing timestamps of console.log inside the callback and on the first line of the new tab's content scripts, as #wOxxOm mentioned.
I just suggest moving message logic to background (event) page and starting the message passing from newtab-contentscript.js, in which you could control when to start sending the message.
A sample code
background.js
let source = null;
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// sent from another content script, intended for saving source
if(request.action === 'putSource') {
source = request.source;
chrome.tabs.create({ url: 'newtab.html' });
}
// sent from newtab-contentscript, to get the source
if(request.action === 'getSource') {
sendResponse({ source: source });
}
});
newtab-contentscript.js
chrome.runtime.sendMessage({action: 'getSource'}, function(response) {
$('#result').html(response.source);
});

Chrome API : Reloading current tab with a url using method in Content.js

I want to reload the page with url by scanning content of it. I designed this method in javascript to see if the url has specific stirng in it
Content.Js
function init() {
var d = document.location.href;
d = toggleDevMode(d);
return d;
}
function toggleDevMode(url) {
var hasDevModeOn = '?core.apexpages.devmode.url=1';
if (url.indexOf(hasDevModeOn) != -1) {
//toggle
url = url.substring(0, url.lastIndexOf(hasDevModeOn));
} else if (url.indexOf("salesforce.com") == -1) {
url = url + hasDevModeOn;
} else {
url = url;
}
return url;
}
Functionality I want
I want if user click on icon, it run the script calling method I defined in content.js onClick Event and checks url.
Based on Logic I defined here, url will be modified.
I want reload the tab with modified url. I tried this piece of code
chrome.browserAction.onClicked.addListener(function (activeTab) {
var newURL = init();
chrome.tabs.create({
url: newURL
});
});
But it doesn't work. Please advice how can I call these method onclick event
You don't need a content script to do this. Discard your init function. Put your toggleDevMode function together with the following code in a background script. Make sure your manifest specify the activeTab permission.
chrome.browserAction.onClicked.addListener(function (activeTab) {
var newURL = toggleDevMode(activeTab.url);
chrome.tabs.update({
url: newURL
});
});
EDIT: Replace your current permissions section from your manifest by the following:
"permissions": [
"activeTab"
],

Sending message from popup.js in Chrome extension to background.js

What is the proper way to send a message (and get a response) to background.js from popup.js in a Chrome extension? Every method I try ends up with an error that:
"Port: Could not establish connection. Receiving end does not exist."
I would prefer to use chrome.extension.sendMessage() over chrome.extension.connect() with port.postMessage(), but neither method seems to have worked.
What I am trying to do is wire a button in the popup.html to call into some javascript in popup.js which calls back to background.js in an effort to get info about the currentTab() that was topMost (ie:to get the current URL string to show in the popup.html)
Right now in popup.js (wired to the action of the button) I have:
function getURL()
{
chrome.extension.sendMessage({greeting: "GetURL"},
function(response) { tabURL = response.navURL });
$("#tabURL").text(tabURL);
}
In background.js I have:
chrome.extension.onMessage.addListener( function(request,sender,sendResponse)
{
if( request.greeting == "GetURL" )
{
var tabURL = "Not set yet";
chrome.tabs.getCurrent(function(tab){
tabURL = tab.url;
});
sendResponse( {navURL:tabURL} );
}
}
Any ideas?
Just to clarify, we talking about communication between popup page from browserAction and background script?
Anyway you have quite a few errors in your code.
First your totally ignore the fact that all callbacks in chrome api are asynchronous.
In background page
var tabURL = "Not set yet";
chrome.tabs.getCurrent(function(tab){
tabURL = tab.url;
}); //this will be invoked somewhere in the future
sendResponse( {navURL:tabURL} );
//navUrl will be always Not set yet because callback of getCurrent hasn't been called yet
Same in popup.js
chrome.runtime.sendMessage({greeting: "GetURL"},
function(response) { tabURL = response.navURL });//callback will be invoked somewhere in the future
$("#tabURL").text(tabURL)//tabURL will display something totally different from what you have been expected
Second error is that chrome.tabs.getCurrent doesn't give you the current tab selected by user in main window. The docs says:
Gets the tab that this script call is being made from. May be
undefined if called from a non-tab context (for example: a background
page or popup view).
So you will get undefined for all of your requests, because you call it in background page. What you need to do is to use method chrome.tabs.query to obtain currently active tabs.
So after fixing all problems new code should look something like this:
background.js
chrome.runtime.onMessage.addListener( function(request,sender,sendResponse)
{
if( request.greeting === "GetURL" )
{
var tabURL = "Not set yet";
chrome.tabs.query({active:true},function(tabs){
if(tabs.length === 0) {
sendResponse({});
return;
}
tabURL = tabs[0].url;
sendResponse( {navURL:tabURL} );
});
}
}
popup.js
function getURL() {
chrome.runtime.sendMessage({greeting: "GetURL"},
function (response) {
tabURL = response.navURL;
$("#tabURL").text(tabURL);
});
}

malsup jquery form submit on select change

I'm using Malsup's excellent Form plugin to dynamically load search results onto the same page.
It works great with a standard form submit, however I have 2 select elements in my form and would love for the results to update as the select is changed.
My code at the moment is thus:
$(document).ready(function() {
var options = {
target: '#bands-results',
beforeSubmit: showRequest
};
$('#bandsearch').ajaxForm(options);
});
// Show loading message and submit form
function showRequest(formData, jqForm, options) {
$('#bands-results').prepend('<span>Searching</span>');
return true;
}
I haven't seen other examples that do the same.
Help appreciated.
Got it licked with this
$(document).ready(function() {
$("#genre-filter").change(function() {
$("#band_search").submit();
});
// bind to the form's submit event
$('#band_search').ajaxForm({
beforeSubmit: showRequest,
target: '#band_list',
success: function() {
$('#premlim').hide();
}
});
})
function showRequest(formData, jqForm, options) {
return true;
}

Chrome extension - Message Passing

I'm trying to get the info that is set on the Options Page to alter the behavior of my extension.
Basically, if a checkbox on OptionsPage is set to true, the extension runs, otherwise it doesn't.
I'm returning true on the background.html for testing purposes, but still, it doesn't work.
Would you guys help me out? Thanks!
Code being injected to the page:
if(chrome.extension.sendRequest() == 'true')
alert("checkbox set to true");
else
alert("it is disabled");
background.html
<script>
chrome.extension.onRequest.addListener(function(){
return true;
}
</script>
If you have an options page and you want to communicate to the background page, you can simply do, chrome.extension.getBackgroundPage()
Options Page communicating to the Background Page
options.html
var bkg = chrome.extension.getBackgroundPage()
bkg.startExtension();
bkg.stopExtension();
background.html
function startExtension() {
console.log('Starting Extension');
}
function stopExtension() {
console.log('Stopping Extension');
}
Content Script communicating to the Background Page
When you are referring to "Code being injected to the page" is that any website? If so, you would need to use a content script with Message Passing. To do so, you can do this.
content_script.js
chrome.extension.sendRequest({action:'start'}, function(response) {
console.log('Start action sent');
});
background.html
function onRequest(request, sender, sendResponse) {
if (request.action == 'start')
startExtension()
else if (request.action == 'stop')
stopExtension()
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
In any case, message passing is a good read for anyone coming into extensions.