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
Related
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.
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
My contentScript sends a message to backgroundScript which opens a popup/panel/window. This panel loads an external web page.
I'm injecting some javascript in the panel to interact with it.
What I'm trying do achieve now is to send data from the panel to the 'main page' (contentScript).
I have successfully managed to send messages from the panel to the backgroundScript.
What I don't understand/know is how to pass the data from the backgoundScript to the contentScript.
Updated script from #Haibara Ai's comment
manifest.js
{
"name": "My extension",
"version": "0.1",
"manifest_version": 2,
"description": "description",
"permissions": ["activeTab", "tabs","http://*/*","https://*/*"],
"content_scripts": [
{
// Change 'matches' attribute to load content
// script only in pages you want to.
"matches": ["SomeUrl"],
"js": ["jquery.min.js", "contentscript.js", "notifier.js"]
}
],
"background": {
"scripts": ["eventPage.js"],
"persistent": false
}
}
contentscript.js
$(document).ready(function() {
var link = document.getElementById('inputLink');
// onClick's logic below:
link.addEventListener('click', function() {
chrome.runtime.sendMessage({
action: 'createWindow',
url: $('input[name=link]').val()
}, function(message) {
console.log(message);
})
});
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert('a');
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
eventPage.js
chrome.runtime.onMessage.addListener(function(request) {
if (request && request.action === 'createWindow' && request.url) {
chrome.windows.create(
{
url: request.url,
focused: true,
incognito: true,
type: "panel"
}, function (newWindow) {
chrome.tabs.executeScript(newWindow.tabs[0].id, {
file: "jquery.min.js"
}, function() {
chrome.tabs.executeScript(newWindow.tabs[0].id, {
file: "htmlselection.js"
});
});
chrome.tabs.insertCSS(newWindow.tabs[0].id, {file: "htmlselection.css"});
});
} else {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
console.log(chrome.tabs);
chrome.tabs.sendMessage(tabs[0].id, {action: "SendIt"}, function(response) {});
});
}
});
htmlselection.js (injected in the popup/panel/window)
[...]
//After a click within the popup/panel/window
chrome.runtime.sendMessage({ text: 'test' });
[...]
Thank you for your help.
Updated
If you want to send message inside chrome.runtime.onMessage, just use the callback sendResponse or use sender.tab.id as tabId to send back the message.
And there are other problems with your code:
Since you are use Programming injection to inject script, you should declare them in "web_accessible_resources" in manifest.json
"web_accessible_resources": [
"htmlselection.js",
"jquery.min.js",
"htmlselection.css"
]
In your contentscript.js, just remove message part, since you didn't receive anything in this script.
For eventpage.js, use sendResponse instead of tab.query.
else {
console.log("2");
sendResponse({ action: "SendIt" });
}
Previous
Take a look at Message Passing, you could send a message from background page using the following code snippets:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
Fixed version of the snippet:
chrome.tabs.query({active: true, currentWindow: false}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
Set the currentWindow:false and it worked.
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