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?
Related
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.
I want to download a JSON object from within the content script. At first, when I request the download, it downloads one file, but at the second request, it downloads two files; at the third request, three files are downloaded, etc.
Background.js
chrome.browserAction.onClicked.addListener(function (tab) {
download();
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//Alert the message
console.log(request);
chrome.downloads.download({
url: request.method,
filename: request.name
}, function (downloadId) {
});
//You have to choose which part of the response you want to display
// ie. request.method
//alert('The message from the content script: ' + request.method);
//Construct & send a response
sendResponse({
response: "Message received"
});
});
});
function download() {
chrome.tabs.executeScript(null, {
file: "jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "content_script.js"
});
});
}
Content Script
function sendMessage(url, filename) {
//Construct & send message
chrome.runtime.sendMessage({
method: url,
name: filename
}, function (response) {
//Alert the message
//You have to choose which part of the response you want to display
// ie. response.response
//alert("The response from the background page: " + response.response);
});
}
var json = JSON.stringify(ticket);
var blob = new Blob([json], {
type: "application/json"
});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.textContent = "Download backup.json";
var container = document.getElementById('ticketDetail');
//container.appendChild(a);
var fName = ticket.date.replace(".", "_")
sendMessage(url, fName.replace(".", "_") + ".json");
As is usually the case with this pattern of problem, the issue is that you are adding multiple anonymous listeners to an event. Specifically, you are adding yet another chrome.runtime.onMessage listener each time the action_button is clicked. You need to add the listener only once.
The simple solution to this is to just add the chrome.runtime.onMessage once:
chrome.browserAction.onClicked.addListener(function (tab) {
download();
});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//Alert the message
console.log(request);
chrome.downloads.download({
url: request.method,
filename: request.name
}, function (downloadId) {
});
//You have to choose which part of the response you want to display
// ie. request.method
//alert('The message from the content script: ' + request.method);
//Construct & send a response
sendResponse({
response: "Message received"
});
});
function download() {
chrome.tabs.executeScript(null, {
file: "jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "content_script.js"
});
});
}
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
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 });
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