I'm so close to finishing my Chrome extension. I have one or two things to do. One of them is sending a message from the content script to the background script. I wrote the following, but it doesn't quite what I want.
content.js
var a=document.getElementsByTagName('a');
for (i=0,len=a.length;i<len;i++) {
a[i].addEventListener('contextmenu', function() {
var linkTitle = this.getAttribute('title').trim();
var linkUrl = this.getAttribute('href');
if ((linkTitle != null) && (linkTitle.length > 0)) {
chrome.extension.sendMessage({action:'bookmarkLink', 'title':linkTitle, 'url': linkUrl}, function(msg) {
alert('Messages sent: '+action+' and '+linkTitle+' also '+linkUrl);
});
}
});
};
background.js
chrome.contextMenus.create({'title': 'Add to mySU bookmarks', 'contexts': ['link'], 'onclick': mySUBookmarkLink});
function mySUBookmarkLink(info, tab) {
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'bookmarkLink') {
chrome.storage.sync.set({'title': msg.linkTitle, 'url': msg.linkUrl}, function(msg) {
alert('Saved '+msg.linkTitle+' to bookmarks');
});
}
});
};
My problems are:
In the first code block, it alerts Saved undefined to bookmarks as soon as I right click on the link, while as I understand it should only send a message on right click and the second code block should alert Saved to bookmarks when I click on the context menu. What am I missing or doing wrong?
I may not have used parameters correctly (I am fairly new to extension development and Javascript in general). Do the above look okay?
Thank you in advance,
K.
It's chrome.runtime.sendMessage and chrome.runtime.onMessage rather than chrome.extension.
There used to be chrome.extension.sendRequest and chrome.extension.onRequest which have been deprecated in favor of the chrome.runtime API methods mentioned above.
See Chrome Extensions - Message Passing
it's JSON-serializable messaging, where first pair is for recognition, and then followed by pairs of
key: value.
You pull the value from received message by calling it's key.
is should be:
alert('Saved '+msg.title+' to bookmarks');
or even better:
function mySUBookmarkLink(info, tab) {
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'bookmarkLink') {
var receivedValue = msg.title; //pull it out first, for better overview
chrome.storage.sync.set({'title': msg.title, 'url': msg.url}, function(msg) {
alert('Saved '+receivedValue+' to bookmarks');
});
}
});
};
Related
In my Chrome extension, I'm trying to exchange data between an internal web page of the extension chrome-extension://myExtensionId/path/to/web/page.html and content scripts.
So, in order to make this data persistent among different content scripts, I'm trying to save it as global variables in the extension's background! I do so using message passing.
My problem is:
When I try to send a response back from the background I get this error:
Error in event handler for (unknown): TypeError: sendResponse is not a
function
I followed the documentation's examples and this is my attempt:
In the scriptOfTheInternalPage.js :
var message = {
'order': 'setData',
'varName': 'myArray',
'data': myArray
};
extPort.postMessage(message, function (response) {
console.log('response:\n', JSON.stringify(response));
});
In background.js :
var globals = {
'myArray': [],
...
};
chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(
function (message, sender, sendResponse) {
console.log(
'the port received this message:\n', JSON.stringify(message), '\n',
(sender.tab) ? ' from tab #' + sender.tab.id : ' from the extension!'
);
if (message.order === 'setData') {
globals[message.varName] = message.data;
sendResponse({'response': 'data saved!'}); //<=====
}
return true; //<=== tried to return true here as well;
});
});
Does this error means I should create a brand new function outside of the onMessage event listener?
I'm confused! What am I missing?
Port's onMessage event listeners do not have the same signature as runtime.onMessage. You don't get sender and sendResponse parameters, only the message. Returning true has no effect either.
To reply to a message, you need to use the port itself. This is covered by examples:
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
}
So you do need an onMessage listener on both sides, and some way to track requests (unique ID?) if several can be made.
I am trying to send a message from a content script to my background script. When the background receives the message it sends data back to the content script in the callback.
My popup also has a listener for messages from the content script, but does not respond to a message meant for the background script.
Then content is receiving an undefined back from the callback, which I think is caused by the popup receiving the message but not responding.
The reference says:
Note: If multiple pages are listening for onMessage events, only the
first to call sendResponse() for a particular event will succeed in
sending the response. All other responses to that event will be
ignored.
So surely I should only get the response from my background script.
My content script does this:
function notifyReady() {
chrome.runtime.sendMessage({
type: 'ACTIVITY_HISTORY_READY'
},
function (response) {
console.log(">>>>Response: ", response);
if (response.type == 'HISTORY_DATA') {
processLog(response);
}
});
}
My background script listens like this:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log("received " + msg.type);
if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
if (historyData) {
sendResponse({
type: "HISTORY_DATA",
position: historyData.position,
company: historyData.company
});
historyData = '';
} else {
sendResponse({
type: "NO_DATA"
});
}
}
});
And the listener in my popup is:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.type == 'JOB_DETAILS') {
sendResponse("OK!");
document.getElementById('position').value = msg.position;
document.getElementById('company').value = msg.company;
document.getElementById('url').value = sender.tab.url;
}
});
if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
note that if historyData is falsey you are not sending any response. The else branch of the second if can never be taken.
You should remove historyData from the first if. The popup code has nothing to do with this.
This question already has an answer here:
Clipboard Copy / Paste on Content script (Chrome Extension)
(1 answer)
Closed 6 years ago.
Quick summary
The code below is a file called popup.js. It listens for a click, and sends a message to background.js. Background.js executes another script, and a variable is created.
I somehow need to pass this variable back to popup.js, and continue within the userHasClicked function. The way it is now the response I get is "undefined", and there's nowhere to go from there.
var theParent = document.querySelector("#MENY");
theParent.addEventListener("click", userHasClicked, false);
function userHasClicked(e) {
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
chrome.runtime.sendMessage({type: "ResponseType", directive: clickedItem}, function(response) {
console.log(response);
this.close();
});
};
e.stopPropagation();
}
Routine:
User clicks on an option in popup.html
Event("click") -> sendmessage("type of click")
background.js listens for the message, and executes content.js
content.js creates the variable and can send it back to anyone who listens.
The problem:
The variable must come as a response argument to step 2 (within eventloop)
Save the response as variable.
document.execCommand("copy").
Done
This code below is the relevant part of background.js.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.type) {
case "ResponseType":
var LoggType = request.directive;
console.log(LoggType)
chrome.tabs.executeScript(null, {
code: 'var LoggType = "'+LoggType+'";'
}, function() {
chrome.tabs.executeScript(null, {file:"content.js"});
});
chrome.runtime.onMessage.addListener(function(req, snd, sndRes) {
if (req.type = "LogIsGenerated") {
var Logg = req.directive;
console.log(Logg);
} sndRes({});
});
if (typeof Logg !== "undefined") {
alert("Feedback from content.js received");
sendResponse({type: "FinalVar", directive: Logg});
}
else {
alert("No feedback received");
sendResponse({});
};
break};
return true;
}
);
content.js ends with this line.
chrome.extension.sendMessage({type: "LogIsGenerated", directive: Logg});
Logg is the variable containing the text string I want to add to the clipboard.
At the moment this the code below alerts for No feedback received.
chrome.runtime.onMessage.addListener(function(req, snd, sndRes) {
if (req.type = "LogIsGenerated") {
var Logg = req.directive;
console.log(Logg);
} sndRes({});
});
if (typeof Logg !== "undefined") {
alert("Feedback from content.js received");
sendResponse({type: "FinalVar", directive: Logg});
}
else {
alert("No feedback received");
sendResponse({});
};
Rob W presented a solution here: Background script can write to clipboard in a very simple manner
Worked excellently.
I am developing a chrome extension, here are the main files:
background.js
getPageDimension = function (){
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, { message: "DIMENSION" }, function(response){
if (response != null) {
console.log(response.x);
console.log(response.y);
console.log(response.w);
console.log(response.h);
}else{
console.log('Response is null');
}
});
});
};
content.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.message && (msg.message == "DIMENSION")) {
var dimension = getPageDiemension(document.documentElement);
console.log(dimension.x);
console.log(dimension.y);
console.log(dimension.w);
console.log(dimension.h);
sendResponse({x: dimension.x, y: dimension.y,w: dimension.w,h: dimension.h});
}
});
getPageDiemension = function(currentDom){
var dimension = new Object();
dimension.x = 0;
dimension.y = 0;
dimension.w = currentDom.scrollWidth;
dimension.h = currentDom.scrollHeight;
return dimension;
}
So my aim is to get the full height and width of page loaded in current active tab. When I debug my content script, I get the proper response in my background.js, but if run the script without debugging, I get an undefined response in my background.js.
Here is the declaration of my cotent.js in my manifest.json file:
"content_scripts": [{
"all_frames": true,
"matches": [
"http://*/*", "https://*/*"
],
"js": ["content.js"]
}],
Kindly help me, where am I going wrong?. Let me know if you need any further data.
Issues
There are two little problems in your code, which I found after a wile, since that it looks perfectly working (when it isn't at all).
You're using the deprecated chrome.tabs.getSelected(...) method, which you should avoid. Use chrome.tabs.query({active: true, highlighted: true}, ...) instead.
In your chrome.runtime.onMessage listener, in the content script, you are doing some calculations before sending the response: this makes the message channel close before you can send a response, and will result in a null response.
Quoting from the official documentation:
This function (sendResponse) 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).
Solution
Now that you know what the problems are, you can easily replace the old tabs.getSelected() with tabs.query(), and add a return true; statement in the handler of the runtime.onMessage event in your content script. The solution is the following, I also lightened the code a bit.
Your background.js:
getPageDimension = function (){
chrome.tabs.query({active: true, highlighted: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { message: "DIMENSION" }, function(response){
if (response !== null) console.log('Response:', response);
else console.log('Response is null');
});
});
};
Your content.js:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.message && (msg.message == "DIMENSION")) {
var dimension = getPageDiemension(document.documentElement);
console.log('Dimension:', dimension);
sendResponse(dimension);
}
return true;
});
getPageDiemension = function(currentDom){
return { x: 0, y: 0,
w: currentDom.scrollWidth,
h: currentDom.scrollHeight
}
}
Working example
You can find a working example I made for testing HERE.
Documentation links
Just for clarity, I'm leaving you some documentation links regarding the APIs involved in this extension that you may find helpful:
chrome.tabs API
chrome.tabs.query method
Chrome extension message passing
chrome.tabs.sendMessage method
chrome.runtime.onMessage event
I try to make some changes on a Chrome extension. I need the extension checks the value and if it is true, then execute a script. If false, then do nothing. I wrote something like this:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(localStorage["statusOfSomething"]){
chrome.tabs.executeScript(tabId, {file: "file.js" ,runAt:'document_end'});
}
});
But this takes the initial value of localStorage["statusOfSomething"] always. So there is an async function to register a listener for "onUpdated". But I need to check the localStorage["statusOfSomething"] value of "now", not the value of the time by registering the listener.
How can I do this?
Edit:
Actually I was trying to check two things:
if the website is in the site list of extension
if this website is enabled for the extension
Now here the full story;
There are some websites, I defined them on background.js file. Let's say;
a.com, b.com ... etc.
var sites = [{
name : "a",
wildcard : ["*://a.com/*"],
js : "a.js"
},{
name : "b",
wildcard : ["*://b.com/*"],
js : "b.js"
}]
and there are statuses of the sites (enable/ disable; true/false)
I think it was good to store statuses by localStorage, so I write as initial value true:
for(var i = 0; i<sites.length; i++){
localStorage[sites[i].name] =true;
}
As option; it was needed to addListener for changes:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if(request.method == "setSite"){
var name = request.site;
var status = request.active;
localStorage[name] = status;
}
return true;
});
If user checks the checkbox for status option of the website, then options.js sends message:
$('#' + name).change(function(){
var status = $(this).is(':checked');
chrome.extension.sendMessage({method: "setSite", site: this.id, active: status}, function(response) {
console.log(response.data);
});
});
Now, back to background.js , for every update of the tab, I need to check these two things together:
1. am I interested in this website?
2. is it enable for me now?
So I wrote:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
var url = tab.url;
for(var i = 0; i<sites.length; i++){
var site = sites[i];
var name = site.name;
var wildcard = site.wildcard;
if(localStorage[name] && testUrl(url,wildcard)){
chrome.tabs.executeScript(tabId, {file: site['js'] ,runAt:'document_end'});
break;
}
}
}
});
Here, I get the value of localStorage[sitename] true
If you are more interested, you can see the code on github (the version)