For some reason console.log that I'm using in my background script are visible in the newtab page console.
Is this suppose to be this way? I thought they should be isolated.
newtab.js
chrome.runtime.sendMessage({
name: 'messageIncoming',
data: 'yo',
});
background.js
chrome.runtime.onMessage.addListener((data, sender) => {
console.log('background onMessages', data);
switch (data.name) {
case 'messageIncoming':
return new Promise((resolve) => {
resolve();
});
default:
break;
}
});
both consoles show same message.
background onMessages ....
Related
I am trying to send a message from background script to content script in my chrome extension. But it looks like the message gets send before the content script is loaded?
This is the error I get when I am using my extension normally:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
This is my background script with the tabs.onUpdated function:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.url) {
console.log(changeInfo.url, tabId)
chrome.tabs.sendMessage(tabId, {
url: changeInfo.url,
type: 'URL_CHANGE'
});
}
});
This is my content script receive function:
chrome.runtime.onMessage.addListener((obj, sender, response) => {
console.log('received', obj)
if (obj.type === 'URL_CHANGE') {
console.log('testestsetst')
getAuth()
getUrlType(obj.url)
} else if (obj.type === 'AUTH') {
getAuth()
} else if (obj.type === 'UN-AUTH') {
removeAuth()
}
});
Whenever I run the extension normally I don't see an output from my content script and I get the error as stated above. However, when I debug the background script and step through the code, I get no error and my content script prints everything correctly. Could this be due to the page needing to load? And if so, how do I solve this?
Solved it by checking for tab complete and sending the url through the tab parameter as follows:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
chrome.tabs.sendMessage(tabId, {
url: tab.url,
type: 'URL_CHANGE'
});
}
});
background.js
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == "install") {
chrome.tabs.create({ url: chrome.runtime.getURL(`onboard-page.html`) }, function (tab) {
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status == 'complete') {
chrome.tabs.onUpdated.removeListener(listener)
// Now the tab is ready!
chrome.tabs.sendMessage(tab.id, "hello")
}
});
});
} else if (details.reason == "update") {
}
});
content-script.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
console.log(message)
});
i am using the latest chrome: Version 100.0.4896.60 (Official Build) (64-bit) on win 10 pro
when i install an extension all works fine.
when i close chrome and reopen, the extensions no long work.
the extensions tab shows for all extensions: "worker service (inactive)"
after click on the reload button of the extension all is ok.
i also tested it with:
https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/examples/hello-world
to make sure that this could be to some settings, i uninstalled chrome, removed all chrome files and reinstalled it.
the issue persists.
friends of mine do not seem to have this issue with the same chrome version.
any suggestions on how to resolve this ?
here the code:
"use strict";
async function sendRequest(request, sendResponse) {
try {
const startTime = Date.now();
const response = await fetch(request.url, request.options);
const time = Date.now() - startTime;
const body = await response.text();
const headers = [...response.headers].map((el) => ({
key: el[0],
value: el[1],
}));
sendResponse({
status: response.status,
body,
headers,
time,
});
} catch (err) {
sendResponse({
err: err.message
});
}
}
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
chrome.storage.sync.get("host", ({ host }) => {
if (host === sender.tab.url) {
if (request.type === "send-request") {
sendRequest(request, sendResponse);
} else if (request.type === "ping") {
sendResponse();
} else {
console.log("bad request type", request.type);
}
} else {
console.log("host not correct", host, sender.tab.url);
}
});
// NOTE: return value required to keep port open for async response
return true;
});
chrome.webNavigation.onBeforeNavigate.addListener(() => {
console.info("service is up 2");
});
chrome.webNavigation.onHistoryStateUpdated.addListener((details) => {
console.log('service is up');
});
This is a known bug. You can read more about it here: https://bugs.chromium.org/p/chromium/issues/detail?id=1271154#c52
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
I'm successfully launching a webauthflow to an social OAuth provider from a service worker background script (as per manifest v3 requirements, background scripts are now full blown service workers)
However I'm unable to send a message back to my content script in what should be the simplest scenario.
Here is my service worker (background.js)
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "login") {
if (user_signed_in) {
console.log("already signed in");
} else {
chrome.identity.launchWebAuthFlow({
url: createOAuthEndpoint(),
interactive: true,
}, function (redirect_uri) {
if (chrome.runtime.lastError) {
sendResponse({
message: "fail"
});
} else {
if (redirect_uri.includes("error")) {
sendResponse({
message: "fail"
});
} else {
//we get here but this message is never sent
sendResponse({
message: "success",
profile: "blah"
});
}
}
});
}
}
return true;
});
And here is my content script...(popupsignin.js)
document.querySelector('#sign-in').addEventListener('click', () => {
chrome.runtime.sendMessage({ message: 'login' }, (response) => {
console.log('got the response'); //this log is never written
if (response.message === 'success'){
console.log(response.profile);
}
});
});
Turns out there was nothing wrong with code. There was(is) just nowhere for me to read the console.log(...) output in the callback method for some reason. I added an alert instead and it fired just fine.
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;
});