Problem in sending a message from content script to popup page - javascript

In the chrome extension, I created a button on the website with the help of content script, when this button is clicked I want to take some information from the website and display it on the popup page but I am not succeeding in doing so.
To do this I send the information that I want to display on the extension as a message from content script to popup, but it fails to do it and returns an error Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. I found out that if the popup page is closed(inactive) it cannot receive any messages. But when I click the button on the website the popup page is always closed. Is there any solution to this problem? Here is the code I have written to send a message.
content.js
// Create a button
var button = document.createElement("button");
button.innerHTML = "Send Message";
// Add an event listener to the button
button.addEventListener("click", function(){
// Send a message to the popup page
chrome.runtime.sendMessage({message: "Hello from the content script!"});
});
// Append the button to the body of the page
document.body.appendChild(button);
popup.js
// Listen for messages from the content script
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// Check the message
if (request.message === "Hello from the content script!") {
console.log("Received message: " + request.message);
}
});

Related

Chrome Extension Error Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist

I have a tab change listener in background script which which will send a message to the content script to preform a set of actions in content script.
My code in background script is
window.chrome.tabs.onActivated.addListener((activeInfo) => {
window.chrome.tabs.sendMessage(activeInfo.tabId, { type: 'getLibraries' }, (data) => {
// do some thing
});
});
content script is
window.chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
switch (message.type) {
case 'getLibraries':
// do something
break;
default:
console.error('Unrecognised message: ', message);
}
});
This is working fine in most cases. When I add the extension to my browser and switch to a previously opened tab, the content script wont be present there as the plugin was not present while loading the tab. At this time the background scrip tries to send message on tab change. Since there is no content script chrome will throw the following error
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist
I need a tab change detection in background script which will send a message to the content script without causing the above error. Is there any way to detect if the content script has loaded from background script?

Can't shoot a response every time extension button is clicked

So I'm just trying to get a response every time the extension button is clicked. So like with AdBlock how this comes down
But instead I'm just trying to do a console.log() every time the button is clicked without any visible popups.
I've tried this so far
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "popup-click":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
file: "real.js", // script to inject into page and run in sandbox
allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
});
sendResponse({}); // sending back empty response to sender
break;
default:
// helps debug when request directive doesn't match
alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
}
}
);
Then my real.js
console.log("Yo");
But sadly I only get a Yo when it launches. Any ideas?
If you don't have a popup (nothing shows when you click the button), then there is an event that will fire when the button is clicked:
chrome.browserAction.onClicked
Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
To use:
// In your background script
chrome.browserAction.onClicked.addListener( function() {
// Do stuff
});
If, however, you do have a popup, then, as the docs mention, this event will not fire. Then your code is more appropriate: you just need to send a message from the popup and catch it in the background script whenever it is opened. See a full example in this answer.

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.

Executing script on a precise tab in Google Chrome extension

I want to execute a script on a precise tab of my browser. This script will give back a value.
I don't know what I have to use. The Doc says that contentScript are called on every loading of a new page. I just want to execute the script once the user clicked on a button in my popup.html.
In your contentScript file add listener like this:
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
//do job
sendResponse(...);
});
And in your popup.html on click event:
chrome.tabs.sendMessage(tabid, "message", function responseCallback(response) {
//...
});
more info http://developer.chrome.com/extensions/tabs.html#method-sendMessage

Message passing: Background script to closing tab

I'm a javascript novice writing my first Chrome extension and I'm stuck on message passing. My extension includes a background script, a browser action icon, and a content script. The content script (a timer that measures the number of second spent in tab) needs to update the background script and change the icon when the tab is closed, but since the content script cannot access the tab onRemove event, it needs to listen for a message from the background script.
Here's how I've set up the background script listener to listen for closed tabs:
// Listen for closed tabs.
chrome.tabs.onRemoved.addListener(function(tab) {
send_closed_message();
});
function send_closed_message () {
chrome.tabs.getSelected(null, function(tab) {
console.log("sending tab_closed to tab " + tab.id);
chrome.tabs.sendRequest(tab.id, {close: true},
function(response) {
console.log(response.timer_stop); });
});
}
And here's the function in the content script that listens for this message.
function main () {
console.log("main()");
timer = new Timer();
timer.start();
// Listen for window focus
window.addEventListener('focus', function() { timer.start(); } );
// Listen for window blur
window.addEventListener('blur', function() { timer.stop(); } );
// Listen for tab close
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url:
"from the extension");
if (request.close === true) {
sendResponse({timer_stop: "stopped"});
timer.stop();
}
});
}
I do not see a response from the content script in the background script console. Since I'm closing the tab, I can't view the content script console. Where is the message going wrong? Is there a better way to debug this? Is there another way the content script could listen for when its tab closes?
I believe the onRemoved on background happens when the tab is already being closed, so probably there is no enough time for the context to receive your message and replay back to the background script.
Maybe is a good idea for the context to keep sending messagens to background every second with its count value. And when the background receives the onRemoved event it simply uses the last received value as the live time of that page.

Categories