Chrome extensions onreadystatechange function doesn't execute - google-chrome-extension

My extension tried to log me in on a certain website when a login button is present. I now want to add a check if the login failed, so the script doesnt loop and instead I can handle it in some other way. My problem is that the check never actually happens.
I want to check by looking for an auth cookie that is set in the responseheader, but it doesn't work, because nothing in the function() actually executes.
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://loginpage.com/login?login=1&password=2", true);
xhr.send();
xhr.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
var cookies = xhr.getResponseHeader("Set-Cookie")
if(cookies.includes("auth=")) {
everythingworks();
} else {
wrongcredentials();
}
}
};

Related

how do I use a XMLHttpRequest to send a request safely to a server

I have written some JavaScript to send a request to a php file which can query or post to a database. I have tried using GET and POST.
function action(theAction) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "queryDB.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () {
// The variable xmlhttp not available here. But since this function is a member of xmlhttp, this=xmlhttp
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
document.getElementById("result").innerHTML =
document.getElementById("result").innerHTML + " " + this.responseText;
}
}
xmlhttp.send("p1=post&p2=" + theAction);
}
function showActivity () {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function () {
document.getElementById("result").innerHTML = this.responseText;
}
xmlhttp.open("GET", "queryDB.php?p1=list");
xmlhttp.send();
}
Both methods work fine but they both can be imitated by simply writing the URL of my php file followed by suitable parameters into a browser address bar. So for the GET example I could write in
https://patience5games.com/php/queryDB.php?p1=list
and I get a little report in the browser window.
This means that it is quite easy for hackers to post fake data to my database. How can I prevent that?
I want to send a message in not such an obvious way. One bodge solution using the POST method would be to have xmlhttp.setRequestHeader("Content-Type", "my message"); which I could decode at the other end. I think. But surely there must be a better way than that?

Why are Ajax calls giving connection refused error in heroku deployment but working fine with localhost?

i have built a node app with mongodb , when i run it with localhost , all ajax requests are being made, and json object is returned successfully too, but when i deployed the app to heroku , all of the ajax calls give error , for example :
unreviewedposts:98 GET http://localhost:3000/approvepostbyadmin/be3 net::ERR_CONNECTION_REFUSED.
this ajax call is made by clicking the button :
<button id="approve" getpost= "be3" role="admin" onclick="approveFunc(this)">approve this post and send to respective posts page</button>
and here is the script :
<script>
var httpRequest;
var status = document.querySelector('#reviewstatus');
var test;
function approveFunc(e){
curPostSlug = e.getAttribute('getpost');
console.log(curPostSlug);
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = approveFuncRequest;
httpRequest.open('GET', 'http://localhost:3000/approvepostbyadmin/'+ curPostSlug);
httpRequest.send();
}
function approveFuncRequest(){
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200 ) {
var resJson = JSON.parse(httpRequest.responseText)
console.log(resJson.reviewed)
status.innerHTML = "resJson.reviewed"
} else {
alert('There was a problem with the request.');
}
} else {
console.log("not ready")
}
}
<script>
This is just one place, it's giving same eroor for all of my ajax requests on all pages whereever i have used them.
The browser is showing error at httpRequest.send().
What could be the reason behind it ,i have set all env variables correctly, is it because i am using localhost:3000 in the request URL's, if yes what should i use there.
How can i get it to work, Any help would be appreciated.

XMLHttpRequest working fine in content script but not in background script - Chrome extension

I'm switching requests from content script to background script and the code is identical but somehow the XMLHttpRequest doesn't keep me logged in.
My goal is to log in a user and change his password - which requires 2 POST requests. The second one fails.
Background script:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
// FIRST REQUEST
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", "https://.../login.php", true);
loginRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
loginRequest.send("user credentials...");
loginRequest.onload = function() {
// SECOND REQUEST
var changeRequest = new XMLHttpRequest();
changeRequest.open("POST", "https://.../changePassword", true);
changeRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
changeRequest.send("old pass... new pass...");
changeRequest.onload = function() {
// ISSUE: changeRequest.responseURL is back at the login page? WHY?
if (changeRequest.responseText.includes("Password successfully changed!")) {
sendResponse({passwordChanged: true});
} else {
sendResponse({passwordChanged: false});
}
}
}
return true;
});
PLEASE NOTE: This code works perfectly fine in the content script!
loginRequest.anonymous = true;
has solved the problem due to unnecessary cookies when sending from background script.

Prevent user to click on browsers back button Angular2

I am working with Angular 2 JS with Typescript. I have a requirement where I don't want to click/navigate to previous page via Browsers back button.
So how we can disable or prevent user to click or move to previous page via browser.
I have tried some example which are available over internet but those are not working properly. Like -
this.router.navigate(['/view'], { replaceUrl: true });
or
this.router.navigate(['/view'], { skipLocationChange: true });
Use this on page load, it will stop user on navigating back from page on which it placed.
put the code as it is in index.html page of the angular
<script type = "text/javascript">
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain()
{
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
</script>

Chrome/FF/Safari extension: Load hidden web page in incognito-like mode

Is it possible to build an 'incognito mode' for loading background web-pages in a browser extension?
I am writing a non-IE cross-browser extension that periodically checks web-pages on the user's behalf. There are two requirements:
Page checks are done in the background, to be as unobtrusive as possible. I believe this could be done by opening the page in a new unfocussed browser tab, or hidden in a sandboxed iframe in the extension's background page.
The page checks should operate in 'incognito mode', and not use/update the user's cookies, history, or local storage. This is to stop the checks polluting the user's actual browsing behavior as much as possible.
Any thoughts on how to implement this 'incognito mode'?
It would ideally work in as many browser types as possible (not IE).
My current ideas are:
Filter out cookie headers from incoming/outgoing http requests associated with the page checks (if I can identify all of these) (not possible in Safari?)
After each page check, filter out the page from the user's history.
Useful SO questions I've found:
Chrome extension: loading a hidden page (without iframe)
Firefox addon development, open a hidden web browser
Identify requests originating in the hiddenDOMWindow (or one of its iframes)
var Cu = Components.utils;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/devtools/Console.jsm');
var win = Services.appShell.hiddenDOMWindow
var iframe = win.document.createElementNS('http://www.w3.org/1999/xhtml', 'iframe');
iframe.addEventListener('DOMContentLoaded', function(e) {
var win = e.originalTarget.defaultView;
console.log('done loaded', e.document.location);
if (win.frameElement && win.frameElement != iframe) {
//its a frame in the in iframe that load
}
}, false);
win.document.documentElement.appendChild(iframe);
must keep a global var reference to iframe we added.
then you can change the iframe location like this, and when its loaded it triggers the event listener above
iframe.contentWindow.location = 'http://www.bing.com/'
that DOMContentLoaded identifies all things loaded in that iframe. if the page has frames it detects that too.
to remove from history, into the DOMContentLoaded function use the history service to remove win.location from history:
https://developer.mozilla.org/en-US/docs/Using_the_Places_history_service
now to strip the cookies from requests in that page use this code:
const {classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, results: Cr, manager: Cm} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var myTabToSpoofIn = Services.wm.getMostRecentBrowser('navigator:browser').gBrowser.tabContainer[0]; //will spoof in the first tab of your browser
var httpRequestObserver = {
observe: function (subject, topic, data) {
var httpChannel, requestURL;
if (topic == "http-on-modify-request") {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
var goodies = loadContextGoodies(httpChannel)
if (goodies) {
if (goodies.contentWindow.top == iframe.contentWindow.top) {
httpChannel.setRequestHeader('Cookie', '', false);
} else {
//this page load isnt in our iframe so ignore it
}
}
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
//Services.obs.removeObserver(httpRequestObserver, "http-on-modify-request", false); //run this on shudown of your addon otherwise the observer stags registerd
//this function gets the contentWindow and other good stuff from loadContext of httpChannel
function loadContextGoodies(httpChannel) {
//httpChannel must be the subject of http-on-modify-request QI'ed to nsiHTTPChannel as is done on line 8 "httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);"
//start loadContext stuff
var loadContext;
try {
var interfaceRequestor = httpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
//var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
try {
loadContext = interfaceRequestor.getInterface(Ci.nsILoadContext);
} catch (ex) {
try {
loadContext = subject.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch (ex2) {}
}
} catch (ex0) {}
if (!loadContext) {
//no load context so dont do anything although you can run this, which is your old code
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var contentWindow = loadContext.associatedWindow;
if (!contentWindow) {
//this channel does not have a window, its probably loading a resource
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
var gBrowser = aDOMWindow.gBrowser;
var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
var browser = aTab.linkedBrowser; //this is the browser within the tab //this is where the example in the previous section ends
return {
aDOMWindow: aDOMWindow,
gBrowser: gBrowser,
aTab: aTab,
browser: browser,
contentWindow: contentWindow
};
}
}
//end loadContext stuff
}

Resources