Chrome Extension Content ->Background message passing - google-chrome-extension

Whats up with this?
content script:
chrome.extension.sendMessage({message: "whats the url"}, function(response) {
alert(response.hereistheurl);
});
background
chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
if (request.message) {
var taburl = sender.tab.url;
alert("the background is trying to send " + taburl);
sendResponse = ({hereistheurl: "taburl"});
}
else {
alert("trying")
var tabnumber = sender.tab.id;
chrome.tabs.update(tabnumber, {url: request.gohere});
}
});
The else is working fine. When the if statement is true,the background tries to send a response, but I see nothing in the content script.

Related

How To detect a specific Extension that communicate with my webpage

In my webpage i want to make a script to detect a specific extension that manipulate my code
I've already tried the following in my webpage
async function tst(){
debugger;
window.addEventListener("PassToBackground", function(evt) {
var blockedExID="bjnkkhimoaclnddigpphpgkfgeggokam";
if (!chrome.runtime) {
// Chrome 20-21
chrome.runtime = chrome.extension;
} else if(!chrome.runtime.onMessage) {
// Chrome 22-25
chrome.runtime.onMessage = chrome.extension.onMessage;
chrome.runtime.sendMessage = chrome.extension.sendMessage;
chrome.runtime.onConnect = chrome.extension.onConnect;
chrome.runtime.connect = chrome.extension.connect;
}
var runtimeOrExtension = chrome.runtime && chrome.runtime.sendMessage ?
'runtime' : 'extension';
var reponse= chrome[runtimeOrExtension].sendMessage(blockedExID,{ message: "version" },{
function (reply) {
if (reply) {
alert(reply);
}
}
});
chrome[runtimeOrExtension].sendMessage({greeting: 'hello'});
}, false);
}
but chrome.runtime is undefiled

How to kill spawn program nodejs based on button in frontend

In the backend, I run a script when user clicks button however, I need the ability for frontend to be able to click button to stop the script. I am using eventSource on the frontend to stream the output of the script to the frontend. I have tried spawn.kill(), kill(), and everything. I can't seem to get it to stop the script. The script still continues even though i close the eventSource and call spw.kill() in the res.socket.on function. Any help will be appreciated!
Frontend code here
const fetchStream = (e) => {
e.preventDefault();
var evtSource = new EventSource(
`http://${process.env.REACT_APP_IP_ADDRESS}/run`
);
evtSource.onmessage = function (e) {
var d = Date.now();
var formatteddatestr = String(moment(d).format("M/D/YYYY-hh:mm:ss a"));
setData((data) => [...data, formatteddatestr + ": " + e.data]);
if (stopTest) {
// I have a button that turns this to true when user clicks it.
evtSource.close();
setStopTest(false);
setData((data) => []);
setRunning(false);
}
if (e.data.includes("Test done.")) {
evtSource.close();
createPDF(e);
}
};
evtSource.onerror = function (e) {
evtSource.close();
setRunning(false);
};
This is backend code
router.get("/", function (req, res) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-control": "no-cache",
// Connection: "keep-alive",
});
// res.write("\n");
var d = new Date(Date.now());
var formatteddatestr = String(moment(d).format("M/D/YYYY-hh:mm:ss a"));
fs.writeFileSync(__dirname + "/start.txt", formatteddatestr);
var spw = spawn("./Validator", ["-d", "tests"], {
cwd: __dirname + "/../../../Validator",
detached: true,
}),
str = "";
var kill = false;
res.socket.on("end", (e) => {
// doesn't work here
// code gets here when user clicks button to stop script
spw.kill();
res.end();
});
spw.stdout.on("data", function (data) {
res.write("data: " + data + "\n\n");
});
spw.stderr.on("data", function (data) {
//works here
spw.kill();
});
});

Unable to update the incoming CloudFront request using Lambda Edge

I am working on a feature where the incoming requests from CloudFront are intercepted using Lambda Edge and then the program checks if there is a jpg file of same name present in S3. If yes, it updates the request to use jpg file otherwise use png file.
In the logs, I see a request coming in and the request getting updated with the jpg url in case a jpg file exists. But, on the webpage I still png file in every case.
Can anybody please advise what I am doing wrong?
Here's the code:
exports.handler = async (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const origin = request.origin;
console.log("Original Request: " + request.uri);
if(request.uri.startsWith('/looks/') && request.uri.endsWith('.png')) {
var jpg_file = request.uri.replace(".png", ".jpg");
console.log("Modified Request: "+ jpg_file);
var jpgFileExists = checkIfFileExists(s3, jpg_file.substr(1));
jpgFileExists.then(function(result) {
const type = result;
console.log("TYPE: " + type);
if(type) {
console.log("send JPG file");
request.uri = jpg_file;
} else {
console.log("send png file");
//do nothing
}
});
}
console.log("FINAL URL: " + request.uri);
return callback(null, request);
};
async function checkIfFileExists(s3, fileName) {
let exist = true;
let params = {
Bucket: "bucketName",
Key: fileName
};
try {
console.log("Checking for file: " + fileName);
await s3.headObject(params).promise();
} catch (err) {
exist = false;
}
console.log("EXISTS: " + exist);
return exist;
}

Tons of Node.js HTTP requests are causing computer to not have internet connection until I restart the process

I have this basic code:
const cookie = require('cookie')
const https = require('https')
const http = require('http')
const proto = { https, http }
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server")
const db = client.db(dbName)
const foos = db.collection('foos')
perform(foos, function(){
console.log('done')
})
})
function perform(a, done) {
const stream = a.find({ url: null })
// emits each line as a buffer or as a string representing an array of fields
stream.on('data', function(doc){
stream.pause()
request(doc.url, function(){
stream.resume()
})
function request(url, fn, redirect, cookies) {
cookies = cookies || {}
console.log(redirect ? 'redirect' : 'start', url)
const val = url.match(/^https/) ? 'https' : 'http'
var headers = {}
if (Object.keys(cookies).length) {
var ck = []
Object.keys(cookies).forEach(key => {
ck.push(cookie.serialize(key, cookies[key]))
})
headers.Cookie = ck.join('; ')
}
proto[val].get(url, { headers }, function(response) {
// console.log(response.headers)
console.log(response.statusCode, url)
if (response.statusCode == 302 || response.statusCode == 301 || response.statusCode == 307 || response.statusCode == 303) {
if (response.headers['set-cookie']) {
response.headers['set-cookie'].forEach(function(str){
var cks = cookie.parse(str)
for (var key in cks) {
switch (key) {
case 'expires':
case 'path':
case 'domain':
break
default:
cookies[key] = cks[key]
}
}
})
}
var newUrl = response.headers.location
if (!newUrl.match(/^https?:\/\//)) {
if (newUrl.match(/\/\//)) {
newUrl = 'http:' + newUrl
} else if (newUrl.match(/\//)) {
newUrl = domain + newUrl
} else {
newUrl = domain + '/' + newUrl
}
}
request(newUrl, fn, true, cookies)
} else {
// do something
fn()
}
}).on('error', function(err) { // Handle errors
console.log(err.message)
fn()
})
}
})
// now pipe some data into it
stream.on('end', function(){
done()
})
}
It essentially just loads a bunch of URLs from the database and makes the call for each. It uses the streaming feature of MongoDB collections so it only does one request at a time, and when the request completes, it starts the next. However, after about 3-5 minutes of running this script, the process hangs. Not only that, the browser I'm using hangs too! I'm running this as a Node.js script, but for some reason it seems to be blocking all the traffic of my computer after 3-5 minutes.
The thing is, when I restart the process (which takes only an instant/second), everything's fine again and the requests go through. Another aspect is, say I try to go to a URL in the browser (any URL, like stackoverflow.com), and it's hanging because of the script. If I restart the process, the browser window completes its request! I have no idea why this is.
Wondering if you know why this might be happening and how I might go about fixing it.

How to access variables from background.js to pop up in chrome extension

in chrome extension, I am creating a new html page as popup through background.js. Check the background.js code below,
chrome.contextMenus.create({
title: "share this",
contexts: ["selection"],
onclick: myFunction
});
var test0 = "Testing content Outside the myfunction";
function myFunction(data) {
var theSelection = data.selectionText;
console.log(theSelection);
chrome.tabs.query({'active': true, "lastFocusedWindow":true}, function(tabs) {
var sourceURL = tabs[0].url;
chrome.windows.create({
url: chrome.runtime.getURL('redirect.html'), type: 'popup'},
function(tab)
{
});
return record;
})
}
I have gone through getbackgroundpage function given here. I am able to access variable test0 with it but not sourceURL (as it is not in window scope).
by redirect popup window code is below,
var bg = chrome.extension.getBackgroundPage();
var sourceURL = bg.sourceURL;
var testvariable = bg.test0;
sourceURL is undefined.
Not getting a clue on how to define variables as global so that access in popup.
is there any better way, we can do it?
Dude , try to use Gogle message passing .
Little example from link before
BackgroundScript
var myFunc = function(){
//some code
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.messageType == "callSomeFunc") {
myFunc();
sendResponse({
status: "Function myFunc called."
});
}
//use return true for async response
return true;
});
contentScript
chrome.runtime.sendMessage({
messageType: "callSomeFunc"
},
function(response) {
// response contain {status: "Function myFunc called."}
console.log(response);
});

Resources