Could not establish connection. Error for chrome extension - javascript

I am making a chrome extension and am trying to get my background script to communicate with my content script each time a tab is update. This is the code I am using
//Background
chrome.tabs.onActivated.addListener(function(activeInfo) {
console.log("Tab with id: " + activeInfo.tabId + " and window: " + activeInfo.windowId + " is now active");
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message : "run", data: "replaceText"}, function(response) {});
});
});
//content
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message === "run") {
console.log("Received message: " + request.message);
Display();
}
})};
//manifest
"permissions": ["tabs","activeTab","nativeMessaging"],
I am still getting the error Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
I have tried deactivating all my extensions and changing code nothing works.

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.

Chrome extension messages not getting through

manifest.json:
{
"manifest_version": 2,
"name": "chrome-extension-bar",
"description": "Chrome Extension Bar",
"version": "1.0",
"browser_action": {
"default_title": "Chrome Extension Bar",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"permissions": [
"<all_urls>",
"tabs"
],
"content_security_policy": "script-src 'self' https://ajax.googleapis.com/ https://maxcdn.bootstrapcdn.com ; object-src 'self'"
}
background.js:
console.log("In background.js")
chrome.runtime.onMessage.addListener (
function (request, sender, sendResponse) {
console.log("In listener");
// to send back your response to the current tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {fileData: response}, function(response) {
sendResponse({farewell: "goodbye"});
});
});
return true;
}
);
content_script.js:
var current_title_bar = document.getElementById("global-nav");
console.log("Title bar:" + current_title_bar);
current_title_bar.appendChild(extension_bar); // <= GODD, getting here
document.getElementById("idStartButton").addEventListener('click', function () {
console.log('Sending start button message: ' + document.getElementById("idNumSecondsPerPage").value);
chrome.runtime.sendMessage({numSecondsPerPage : document.getElementById("idNumSecondsPerPage").value}, function(response) {
console.log('Got response: ' + response.farewell);
});
});
document.getElementById("idStopButton").addEventListener('click', function () {
console.log('Sending stop button message: ' + document.getElementById("idNumPages").value);
chrome.runtime.sendMessage({numPages : document.getElementById("idNumPages").value}, function(response) {
console.log('Got response: ' + response.farewell);
});
});
The messages seem to be getting sent, but there's I'm not getting anything back from the receiver.
Console log on the page into which the form was injected:
Entering content_script.js
content_script.js:156 Title bar:[object HTMLElement]
content_script:161 Sending start button message: 67
content_script:168 Sending stop button message: 76
Why aren't the messages sent by background.js received by content_script.js? Are they even sent?
If you want to send a message from the background.js script to the content_script.js then you need to set an onMessage listener on the content script.
What you might do in this case is, after receiving the event on the background script, just call the callback function, instead you're sending a new event with a callback function than when it is executed, calls the callback function of the first event.
Instead of doing this:
console.log("In listener");
// to send back your response to the current tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {fileData: response}, function(response) {
sendResponse({farewell: "goodbye"});
});
});
just do this
console.log("In listener");
// send back your response
sendResponse({farewell: "goodbye"});

how to send message from background to content script?

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

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