sending a message from content script - google extension - google-chrome-extension

Im trying to send a message on every content load like this:
content.js
chrome.runtime.sendMessage({
data: "just an example"
}, function (response) {
console.dir(response)
});
and then send a message back just to test if it works
popup.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse({
data: "example answet to the message"
});
});
but the problem is im getting undefined as a response in content. Why?
The point of sending a message from content on page load is to set a badge with a number like this:
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
chrome.browserAction.setBadgeBackgroundColor({ color: [255, 0, 0, 255] });
chrome.browserAction.setBadgeText({text: `${blockedUsersFromStorage.split(',').length}`});
});

Related

How to set input on chrome extension to text from dom?

I am trying to get text from the web page on click into the input on my chrome extension.
Content script
document.addEventListener('click', function (e) {
let target = e.target
let text = target.textContent || target.innerText;
chrome.runtime.sendMessage({ text }, function (response) {
console.log(response.farewell);
});
}, false);
and background script
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
document.getElementById("userinput").value = "My value";
sendResponse({ farewell: request.text });
}
);
My popup.html just has id of 'userinput' and i am getting unchecked runtime.lastError: The message port closed before a response was received. Error

difference between chrome.runtime.onmessage and chrome.runtime.port onmessage event

My below contentscript.js receives the message only to chrome.runtime.onMessage.addListener but not to port.onMessage.addListener
console.log("loaded");
var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
port.postMessage({answer: "Madame... Bovary"});
});
chrome.runtime.onMessage.addListener(function (msg, sender, response) {
console.log("cs:on message ");
});
I send the following message from my backgroundscript.js:
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log("message sent");
});
});
Why doesn't my port.onMessage.addListener not triggered though its initialized.
From https://developer.chrome.com/extensions/messaging :
In order to handle incoming connections, you need to set up a
runtime.onConnect event listener. This looks the same from a content
script or an extension page. When another part of your extension calls
"connect()", this event is fired, along with the runtime.Port object
you can use to send and receive messages through the connection.
Here's what it looks like to respond to incoming connections:
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});
So this is how you would catch your message from the specific port:
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
console.log(msg) // msg object will be your message
})
})

"chrome.runtime.onMessage" : Send response before create new tab [duplicate]

This question already has answers here:
Chrome Extension Message passing: response not sent
(3 answers)
Closed 7 years ago.
I have problem with sending response in chrome.notifications.onClicked.addListener.
content_scripts
chrome.runtime.sendMessage({action:'openlink', url:'http://stackoverflow.com'}, function(response) {
console.log(response);
});
background
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request && request.action === 'openlink') {
chrome.notifications.create('MyUniqueID',{
type: 'basic',
title: 'Open link',
message: request.url,
iconUrl: 'icon.jpg'
});
chrome.notifications.onClicked.addListener(function('MyUniqueID') {
sendResponse({action:'notification-clicked'}); // <--- This
chrome.tabs.create({url:request.url});
});
}
});
So I was wondering what I did wrong ?
The sendResponse must be used immediately after received the message as a way to reply to the sender: ok I received your message and it's OK, so you continue with your code.
When you need to send a message like in your situation you need to call again the function:
chrome.tabs.sendMessage
This means to have the chrome.runtime.onMessage.addListener in the background and content.
For reference see: Chrome Extension Message Passing
Nah, Just add return true after
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request && request.action === 'openlink') {
chrome.notifications.create('MyUniqueID',{
type: 'basic',
title: 'Open link',
message: request.url,
iconUrl: 'icon.jpg'
});
chrome.notifications.onClicked.addListener(function('MyUniqueID') {
sendResponse({action:'notification-clicked'}); // <--- This
chrome.tabs.create({url:request.url});
});
return true;
}
});

How to send responses from onMessageExternal Listener?

I am sending a message from a content script to my extension using chrome.runtime.sendMessage.
Content Script:
chrome.runtime.sendMessage(extensionId, {
"some" : "request"
}
},
function(response) {
alert("got response");
}
);
The receiving part in the background script looks like that:
Background Script A
chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
console.log("send response");
sendResponse({
"some" : "response"
});
});
This works well: send response is logged to the console of the background page and I receive the alert got response from the content script.
I then introduced some asynchronous JavaScript to the listener:
Background Script B
chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
window.crypto.subtle.generateKey({
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: {
name: "SHA-256"
}
}, false, ["sign"]).then(function(keyPair) {
console.log("send response");
sendResponse({
"some" : "response"
});
});
});
here the callback is called regularly (meaning, send response is logged to the console of the background page after completion. The content script however never receives the response (i.e. there is no got response alert).
What am I doing wrong here? Why is the responseCallback called in A but not in B? That's exactly what the callback chain is made for or isn't it?
This seems to be a bug/feature in chrome. Apparently you need to return true, otherwise the message channel will be closed:
https://developer.chrome.com/extensions/runtime.html#event-onMessageExternal
This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).
Adding return true; to the background script like this solves the issue:
chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
window.crypto.subtle.generateKey({
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: {
name: "SHA-256"
}
}, false, ["sign"]).then(function(keyPair) {
console.log("send response");
sendResponse({
"some" : "response"
});
});
return true;
});

Send one Chrome Extension desktop notification at a time

I am still learning how to create Chrome extensions, but my issue is with the desktop notifications. I am able to trigger the notifications, but when that happens for example I trigger desktop notification for content script 1. The desktop notification also triggers for content script 2. How do I make it so that they do not trigger at the same time, and only when they are called?
Background page
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// Create a simple text notification
var notifyWinner = webkitNotifications.createNotification('48.png', 'Notification', request.winnerMessage);
notifyWinner.show();
setTimeout(function(){ notifyWinner.cancel(); },10000);
});
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// Create a simple text notification
var notifyVideo = webkitNotifications.createNotification('48.png', 'Notification', request.videoMessage);
notifyVideo.show();
setTimeout(function(){ notifyVideo.cancel(); },10000);
});
Content Script 1
chrome.extension.sendRequest({winnerMessage: "You won!!!"}, function(response) {
return response;
});
Content Script 2
chrome.extension.sendRequest({videoMessage: "There is a video" + videoURL}, function(response) {
return response;
});
You can simplify the code to only use one onRequest listener and then it will stop displaying duplicate notifications.
background_page
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// Create a simple text notification
var notify = webkitNotifications.createNotification('48.png', 'Notification', request.message);
notify.show();
setTimeout(function(){ notify.cancel(); },10000);
});
content_script
chrome.extension.sendRequest({
message: "There is a video" + videoURL}, // Change the message here as needed.
function(response) {
return response;
});

Resources