Chrome Extension unable to send message from background to content script successfully - google-chrome

I am trying to create an extension that, in the background script, opens a specified URL, and then sends a message to said tab that was opened in the content script side, but I am getting an error and I'm not sure where I'm going wrong.
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
background.js
let targetTab = "http://google.com"
main();
function main() {
let active = true;
let tabId = null;
let tabUrl = null;
if (active) {
chrome.tabs.create({
url: targetTab,
}, (tab) => {
console.log("Tab ID Generated: " + tab.id);
tabId = tab.id;
chrome.tabs.query({}, function (tabs) {
tabs.forEach(tab => {
console.log(tab.url);
if (tab.url !== targetTab) {
chrome.tabs.remove(tab.id);
}
})
console.log("Tab ID Sent: " + tabId);
chrome.tabs.sendMessage(tabId, {
tabId,
tabUrl,
}, (response) => {
console.log(JSON.stringify(response));
})
})
})
}
}
content.js
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
}
console.log("Got Message");
sendResponse({message: "hi to you"});
});

Related

chrome google extension send message data from background to ui

I have read several forums here , here, and here but didn't solve my issue.
On load, I need to pass the data from background.js (coming from an api response) to my content script so that It would populate my dropdown menu. I have tried several codes but nothing worked. It doesn't have error, just that nothing happens.
the following commented and un-commented codes inside sendTocontent are what I have tried in background.js. Pls note that if I use the tabs[0].id - this is empty array or sometimes not defined so I had to work around for the lasttabid - I figured this must be the issue but how ??? That's all I see in the documentation.
background.js
var lastTabId = -1;
function sendMessage() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
lastTabId = tabs[0].id;
chrome.tabs.sendMessage(lastTabId, "Background page started.");
});
}
sendMessage();
let uri=chrome.runtime.getURL('');
chrome.storage.local.set({ "chrome_uri" :uri })
chrome.runtime.onMessage.addListener(function(request, sender) {
var environment = "http://localhost:9126/";
$.ajax({
url: environment + "Plugin/list",
type:'get',
success:function(data){
var profiles = JSON.parse(data.Content);
sendTocontent(profiles);
}
})
});
function sendTocontent(somedata){
// chrome.tabs.query({currentWindow: true},
// function(tabs) {
// chrome.tabs.sendMessage( tabs[0].id, {sender:'background', somedata:somedata});
// })
// chrome.extension.sendMessage({somedata: "hello"}, function(response) {
// console.log(response);
// });
// chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
// chrome.tabs.sendMessage(lastTabId, {action: "open_dialog_box"}, function(response) {});
// });
chrome.tabs.sendRequest(
lastTabId,
{'profileList': true});
}
this is my contentscript called toolbar.js:
//i tried this
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.sender=='background') {
alert("Request sent sucesss")
}
});
//i tried this
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
chrome.pageAction.show(sender.tab.id);
}
);
function onExtensionMessage(request) {
if (request['profileList'] != undefined) {
alert("onExtensionMessage")
}
}
//i tried this
chrome.extension.onRequest.addListener(onExtensionMessage);
excerpt from my manifest:
"background" : {
"scripts" : ["js/jquery.js","background.js"]
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["js/jquery.js","js/toolbar.js"],
"css": ["button.css"]
}
],
permissions": ["storage", "activeTab", "tabs"],
The correct solution is actually trivial.
The content script sends a message to the background script.
chrome.runtime.sendMessage({action: 'getProfiles'}, profiles => {
console.log(profiles);
//useProfiles(profiles);
});
The background script fetches the URL and responds with the result.
chrome.runtime.onMessage((msg, sender, sendResponse) => {
if (msg.action === 'getProfiles') {
fetch('http://localhost:9126/Plugin/list')
.then(r => r.json())
.then(json => sendResponse(json.Content));
// keep the channel open for sendResponse while `fetch` runs asynchronously
return true;
}
});
Yep, this is the entire code.

Pause chrome.webRequest.onBeforeRequest until message | Chrome extension

I am working on a chrome extension and I am having trouble pausing web requests until message is received from Script.js.
chrome.webRequest.onBeforeRequest.addListener(function (e){
chrome.tabs.executeScript(null, {code:"var eventURL = JSON.parse('" + encodeToPassToContentScript(e) + "');"}, function(){
chrome.tabs.executeScript(null, { code:`(async function() {
//console.log('E URL', eventURL.url);
if (eventURL.url.match("some condition")){
var iframe = document.createElement('iframe');
iframe.src = url ;
document.body.prepend(iframe);
iframe.addEventListener("load", function() {
console.log('Iframe loaded');
// Gather data
chrome.runtime.sendMessage(extraData, function(response){
console.log('extraData', extraData);
console.log('response sent', response);
});
});
}
})()`}, () => {
new Promise(resolve => {
chrome.runtime.onMessage.addListener(function listener(result) {
chrome.runtime.onMessage.removeListener(listener);
console.log('RES', result)
resolve(result);
});
}).then(result => {
console.log('RES', result);
});
});
})
return {cancel: false};
}, {
urls:["<all_urls>"],
types:["xmlhttprequest"]
}, ["blocking","requestBody"]);
I have the code above. My goal is filtering web request -> prepending iframe to the current tab, gathering some data from Iframe -> sending message to background.js -> continue the web request.

Changed request does not work in angular 6

I have following function which calls the refresh service to get new token for authorization:
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if(!this.isRefreshingToken) {
this.isRefreshingToken = true;
return this.authService.refreshToken()
.subscribe((response)=> {
if(response) {
const httpsReq = request.clone({
url: request.url.replace(null, this.generalService.getUserId())
});
return next.handle(this.addTokenToRequest(httpsReq, response.accessToken));
}
return <any>this.authService.logout();
}, err => {
return <any>this.authService.logout();
}, () => {
this.isRefreshingToken = false;
})
} else {
this.isRefreshingToken = false;
return this.authService.currentRefreshToken
.filter(token => token != null)
.take(1)
.map(token => {
return next.handle(this.addTokenToRequest(request, token));
})
}
}
When the response is not undefined and request is returned back it does not call the new request
Ok the thing was that the bearer was quoted like below:
But I have still one issue the request does not invoke the new request, when I refresh the page it gives data with new token, instead like I previously had unauthorized error.

Chrome-extension: How to send message from content.js to popup.js - Page_Action

Chrome v64.
I want to send a message from content.js to popup.js.
I managed to send a message from popup.js to content.js. But how to do it the opposite way? I have also downloaded a sample extensions, which also don't work.
Do I have to add a special permission?
I tried one time messaging and long running message channel.
Permissions:
"permissions": [
"background",
"tabs",
"activeTab",
"storage",
"webRequest",
Content.js
chrome.runtime.sendMessage({
data: "mauzen"
}, function (response) {
return true;
});
debugger;
var port = chrome.runtime.connect({
name: "knockknock"
});
port.postMessage({
joke: "Knock knock"
});
port.onMessage.addListener(function (msg) {
debugger;
if (msg.question == "Who's there?")
port.postMessage({
answer: "Madame"
});
else if (msg.question == "Madame who?")
port.postMessage({
answer: "Madame... Bovary"
});
});
Background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
sendResponse({
data: "background"
});
if (request.data === "success") {
alert("success");
} else {
//alert(request.data);
}
});
console.assert(port.name == "knockknock");
port.onMessage.addListener(function (msg) {
if (msg.joke == "Knock knock")
port.postMessage({
question: "Who's there?"
});
else if (msg.answer == "Madame")
port.postMessage({
question: "Madame who?"
});
else {
port.postMessage({
question: "background"
});
}
});
Popup.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse({
data: "popup"
});
if (message.data === "success") {
alert("success");
} else {
// alert(message.data);
}
});
chrome.runtime.onConnect.addListener(function (port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function (msg) {
if (msg.joke == "Knock knock")
port.postMessage({
question: "Who's there?"
});
else if (msg.answer == "Madame")
port.postMessage({
question: "Madame who?"
});
else {
port.postMessage({
question: "popup"
});
}
});
});
This is what I found out, testing around a bit.
To send a message from the content.js script to your popup you do the following:
chrome.runtime.sendMessage({
data: "Hello popup, how are you"
}, function (response) {
console.dir(response);
});
and in your popup.js:
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse({
data: "I am fine, thank you. How is life in the background?"
});
});
The message sent from content.js to popup.js will only be received, when your Popup is active (=open), i.e. you click on your page_action (browser_action) icon in the toolbar and the popup appears, then it is open/active. And only then, it can send and receive messages!
You can test it like this
Put the following script in you content.js:
var timer = 0;
var si = setInterval(() => {
try {
chrome.runtime.sendMessage({
data: "Hello popup, how are you"
}, function (response) {
console.dir(response);
});
timer++;
if (timer === 5) {
clearInterval(si);
}
} catch (error) {
// debugger;
console.log(error);
}
}, 2000);
and in your **popup.js:**
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
alert("I am popup!");
sendResponse({
data: "I am fine, thank you. How is life in the background?"
});
});
As long as the setInterval executes you can click on your extension icon, to open the popup, then it will show an alert.
From your code it looks like you are sending a message from your content script to the background and popup script, as opposite to what you described.
Sending a message from your extension to content script requires you to use chrome.tabs.sendMessage, see https://developer.chrome.com/apps/messaging

Change file name of toStream() in node.js html-pdf npm module

I am trying to change the file name of the pdf generated by the npm module html-pdf.
The issue is I do not want to save a copy of the pdf, just stream it to an email service ( mailgun) and then send it off. I have everything working but when I receive the email the file has a default name that I want to change. Does anyone have any experience trying to do this?
Thanks
var pdf = require('html-pdf');
var Mailgun = require('mailgun-js');
pdf.create(result).toStream(function(err, stream) {
var self = this;
if (err) return console.log(err);
//set mailgun parameters
var mail_data = {
from: 'emailtosendto#email.com',
to: 'sendingemail#email.com',
subject: 'subject line',
html: result,
attachment: stream
}
//send email
mailgun.messages().send(mail_data, function (err, body) {
if (err) {
res.render('error', { error : err});
console.log("got an error: ", err);
}
else {
console.log(body);
res.send('ok');
}
});
});
var pdf = require('html-pdf');
var Mailgun = require('mailgun-js');
pdf.create(result).toBuffer(function(err, buffer) {
var self = this;
if (err) return console.log(err);
var attch = new mailgun.Attachment({data: buffer, filename: 'myattach.pdf'});
//set mailgun parameters
var mail_data = {
from: 'emailtosendto#email.com',
to: 'sendingemail#email.com',
subject: 'subject line',
html: result,
attachment: attch
}
//send email
mailgun.messages().send(mail_data, function (err, body) {
if (err) {
res.render('error', { error : err});
console.log("got an error: ", err);
}
else {
console.log(body);
res.send('ok');
}
});
});
From https://github.com/bojand/mailgun-js#attachments