how to send message from background to content script? - javascript

i am sending message from background to content script.
My background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
switch(request.type){
case "login-check":
checkLogin();
break;
}
});
function checkLogin() {
// var test = localStorage.getItem("test");
// alert(test);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {type: "login"}, function(response) {
console.log(response.farewell);
//alert(response.farewell);
});
});
}
My content-script.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "login")
sendResponse({farewell: "goodbye"});
});
it is showing me an error "Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined
".
i have tried all the ways almost but it didn't work please help.
thanks in advance

Related

Javascript send message from content.js to background.js

I read some of the chrome docs and got this basic example working.
Now I want to make the request based on an event happening. The event is triggered and contentUpdateData() runs, but the chrome.runtime.sendMessage within the function doesn't seem to work. Any ideas why?
/* content.js */
var data = []
chrome.runtime.onMessage.addListener(
function(request, sesnder, sendResponse) {
if (request.message === 'popupClicked') {
contentUpdateData();
}
}
)
function contentUpdateData() {
console.log('Code works up to here. Button clicked in popup.html, recieved in content.js. Need to get info from background.js')
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
data = response.data
});
}
/* background.js basic example from chrome */
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting === "hello")
sendResponse({farewell: "goodbye", data: null});
}
);
You need to return true from the event listener in backgroundjs. This saves sendResponse() from garbage collection.
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.greeting === "hello") sendResponse({ farewell: "goodbye", data: null });
// VERY IMPORTANT
return true;
});
Somehow the background.js did not sync properly after updating the extension. This was the cause for the error.

popup.js can`t receive messages from background Chrome extension

I try this:
background.js
receive messages from popup.js (work fine)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('chrome.runtime.onMessage');
console.log(request);
if (request&&request.method&&request.action) {
if($.isFunction(getLr()[request.method][request.action])) {
sendResponse(getLr()[request.method][request.action](request.data?request.data:undefined));
} else {
sendResponse(getLr()[request.method][request.action]);
}
}
});
send data to popup.js (don't work)
chrome.tabs.query({active: true}, function(tabs){
for(let t in tabs) {
chrome.tabs.sendMessage(tabs[t].id, $.extend({}, {method: method}, data), callback);
}
});
popup.js
send to background script (work fine)
chrome.runtime.sendMessage({method: method, action: action, data: data}, callback);
receive from background (don't work)
window.onload = function () {
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('chrome.runtime.onMessage');
});
};
what wrong?

Chrome extension modify newtab page body?

I have chrome extension, which add new div to page body. But it doesnt work when i`m trying to run it on newtab page.
Here is my background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "commonAddWidget.js"};
});
I found that it can be resolved by adding content script, and sending a message to it after clicking on extension icon on browser.
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
if (url.indexOf('chrome://newtab') > -1) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {someObject: someValue});
});
}
}); });
contentScript.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {// this code can modify NewTab page, and will modify only it });

How to send a message between Chrome extension popup and content script?

Following the Google tutorial, I am sending a message from a popup script to a content script. The message passes correctly but when I call the response callback I get the following error:
Attempting to use a disconnected port object
This is popup.js:
chrome.tabs.query(
{ active: true, currentWindow: true },
function(tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{ greeting: "hello" },
function(response) {
console.log(response);
});
});
This is content.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
sendResponse('goodbye'); // <- Error here
});
How can I send this message and get the response back?
This turned out to be due to an alert on the content page which caused the popup window to close. This in turn breaks the connection between the popup and the content script.
This example demonstrates sending a message to the content script in the selected tab.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
reference Link

How to retrieve the active tab, inside message listener in background, in chrome extension?

I'm using the following code (in background.js) to get the active tab
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
console.log("active tab retrieved : " + tabs[0].id);
});
This works great, except for one case: when this piece of code is inside a messaging listener. For example the next scenario:
In background.js
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
console.log("message received");
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
console.log("active tab retrieved : " + tabs[0].id);
});
}
);
*in content_script.js*
chrome.runtime.sendMessage({}, function(response) {});
I only got the following in console
message received
and I didn't get the second log in console.
Why is this happening and how to solve it ?
There is an unclosed parenthesis in your code, which raises an exception and aborts execution. Correct it like this:
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
console.log("message received");
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
console.log("active tab retrieved : " + tabs[0].id);
}); // <-- add `);`
}
);
That said, if you just want to get the tab that sent the message, it is much easier:
sender.tab.id

Categories

Resources