Message Passing from Content Scripts to Background Page in Chrome Extensions - javascript

Google Chrome Extensions Message Passing Problem :
In this Chrome Extension
My Popup Page:
chrome.browserAction.onClicked.addListener(getMessage);
getMessage();
function getMessage()
{
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});//getting response from content script
});
}
My Script Page :
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({});
});
I am not getting any response from the content script.
Edits:
As per #serg , i have moved the code to the background page. But still, it is not working

You can't have chrome.browserAction.onClicked listener if you have popup page attached to the browser action button, it won't fire.
Remove popup, leave only button
Move everything into background page.
Replace tab.id with null.
Remove createFile(); call at the beginning as it won't do anything in this case (content script isn't ready to listen yet).
Don't use alerts for debugging extension, use console.log().

Related

Chrome extension window onload jquery

How am I going to write something when user clicks extension icon and loads the window?
I've already tried
window.onload = function() {
console.log("das");
}
and ]
$(document).ready(function(){
console.log('document is ready');
});
but still there isn't any log?
Maybe it's not the best idea but you can use chrome.tabs.sendMessage and chrome.runtime.onMessage.addListener to communicate between contentscript.js and popup.js
contentscript.js is running directly in page scope so you can easily detect when page is ready. After that you can send a message chrome.tabs.sendMessage(tabs.id, {action: 'pageReady'});. In popup.js you are listening to:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'pageReady') {
// Do what you want to do on page ready
}
});
It should works good for you. You can also send response to the caller:
contentscript.js send information to the popup.js that page is ready.
popup.js do what you want to do (show table).
popup.js send information to the contentscript.js that table is added.
EDIT
I'm not sure about my solution because I found information that:
The popup, while being an extension page, is not a background page. It
is only accessible when it is open
I don't know if it is possible to listen on events in popup. You need to check it.

OnActivated is only working when new tab opened

I'm trying to communicate with the content script of the tab that has just been switched to using message passing. Here is my code in the background.js script.
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.sendMessage(activeInfo.tabId, { greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
And here is my code in my content script:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse({ farewell: "goodbye" });
loadContent();
});
Is the content script no longer listening in an inactive tab even when it's switched back to that tab? Why does this only run in a newly opened tab?
To further clarify why I want to do this, sometimes tabs are left open without reloading, and my script has already been executed. When information pertaining to the script changes using the popup options, I want the content to reload on tab change, and a particular function to run again without reloading the page. Therefore, injecting the content script is less than ideal since it's already been executed.
Try this :
background.js
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
chrome.tabs.sendMessage(activeInfo.tabId,
{ greeting: "hello" }, function(response) {
console.log(response.farewell);
});
});
});

open a chrome tab from content script

I need to open a chrome tab using content script.
I checked message passing in chrome example and tried this
In content script:
chrome.runtime.sendMessage({greeting: "hello"}, function (response) {
console.log(response.farewell);
});
And in background.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
chrome.extension.getBackgroundPage().console.log('resp.type');
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello") {
chrome.tabs.create({url: 'http://google.com'});
sendResponse({farewell: "goodbye"});
}
});
It is working well, the problem is that the tab is opening but also lots of tabs get opened...What I need to do to open just one tab?
When you run the content script it also runs in the new tab that you opened so it ends up opening an infinite amount of tabs. To limit this, you can put the tabs.create inside of a function that doesn't run immediately on page load.
The problem is most likely that you are calling the "chrome.runtime.onMessage.addListener" multiple times, so when it does get a message, all the listeners you added are opening a tab, once for each one that was setup.

Messaging between content script and popup script in Chrome extension

I'm trying to create a popup chrome extension that shows information about the DOM in the current page, which seems to require messaging. I've been able to send messages to the background, but I need the data to be specific to the current page, as the background is identical to all popups/pages.
In popup.js, I send a message when the DOM is loaded (should trigger when popup is clicked?)
document.addEventListener('DOMContentLoaded', function() {
chrome.runtime.sendMessage({method: "getTableData"}, function response() {
});
});
I also have a listener in the contentscript.js (and background.js for testing)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request.method == "getTableData") {
console.log("table request found!");
}
});
Then, when I activate the popup, the background console outputs table request found!, while
the console for the current page doesn't.
Thanks.
You need to use chrome.tabs.sendMessage instead of chrome.runtime.sendMessage to send a message to a content script.

How can I communicate between background.js and popup.js?

I have an extension, with a background script:
"background": {
"scripts": ["scripts/background.js"]
},
and a content script:
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["scripts/content_script.js"]
}
],
a popup window (popup.html), and a popup script (popup.js). popup.js is not registrated into manifest,and it deals with popup.html look, and listen for user actions made in popup.html, such as clicking a button.
I want to make an extension, what emails the current tab's page, and for this, I need to get the page DOM with the content_script, pass data (DOM) to the background script. After this, when the user triggers an event in popup.html, popup.js catches this event, and I want popup.js to be able to get the passed data(DOM) from background.js. How could I make this? So, my question is, how could I communicate between background.js and popup.js?
I found an answer to my own question:
Thanks Elvis, I think I solved the problem; I only need to get the DOM of site in content script, but my question's solution was this:
content_script.js
// SEND DOM structure to the background page
chrome.extension.sendRequest({dom: "page DOM here"});
background.html
<html>
<head>
<script>
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.dom != "")
var theDOM = request.dom;
console.log(request.dom); // page DOM here -> works
chrome.extension.sendRequest({theDOM: theDOM}); // theDOM : "page DOM here"
});
</script>
</head>
<body>
</body>
</html>
popup.js
var dom;
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.theDOM != ""){
console.log("popup request: "+request.theDOM);
dom = request.theDOM;
}
});
// HANDLE TAB_1 REQUESTS (EMAIL PAGE)
// ---------------------------------
$("#send").click(function(){
console.log(dom); // page DOM here
}
Thanks for the help ;)
You can do Message Passing. From the documentation:
Use this in your content script:
chrome.extension.sendRequest({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
It sends {greeting: "hello"} to the background. Notice the callback specified
The background page can listen to these requests using:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
The arguments to the sendResponse function will be passed to the callback

Categories