create plugins to detect suspicious ajax - javascript

I want to make browser extension for Firefox that detect the ajax code of of website that load the hidden page and redirect to new page ,like if user visit index.php where ajax load the two pages one is hiddenpage.php and redirect to new.php . Is there any other solution to detect this ajax at client side.
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("myDiv").innerHTML="";
}
}
xmlhttp.open("GET","hidden.php",true);
xmlhttp.send();
}
HTML
click here

document.addEventListener('DOMContentLoaded', function() {
getCurrentTabUrl(function(url) {
fetchData(url);
});
});
function fetchData(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
var data = xhr.responseText;
var index = data.indexOf('XMLHttpRequest');
if(index != -1){
document.getElementById("status").innerHTML = "The page contains AJAX requests";
}else{
document.getElementById("status").innerHTML = "Page doesn't contains AJAX";
}
//document.getElementById("status").innerHTML = data;
}
}
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
//xhr.setRequestHeader("Access-Control-Request-Method", "POST");
xhr.send();
}
function getCurrentTabUrl(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
var url = tab.url;
console.assert(typeof url == 'string', 'tab.url should be a string');
callback(url);
});
}
just go through this code you will get the better help

You can modify XMLHttpRequest's prototype in an userscript.
/* Save the old method somewhere, it may be useful if you want to allow some AJAX */
XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send;
/* Override the previous method to define yours */
XMLHttpRequest.prototype.send = function () {
/* Do stuff here */
alert(1);
/* Use this line if you want to continue the AJAX request */
XMLHttpRequest.prototype._send.apply(this, arguments);
}

Related

How to add variable to xhr.open outta Chrome extension?

I'm writing a Chrome extension, which should on loading of every new domain in browser get special remote url, add to it the current domain (like with window.location.hostname), get special metric from the target page, produced on this way, (with XMLHttpRequest and XPath), and show this metric as BadgeText.
I've got nearly all working, but only with static url. If instead of "+window.location.hostname+" i hardcode any domain name, everything works like expected - i get the number as BadgeText. But how can i get this work with domain currently loaded in browser?
This is my background.js:
chrome.tabs.onUpdated.addListener(function (tabid, changeInfo, tab) {
chrome.tabs.query({ 'active': true, 'currentWindow': true }, function (tabs) {
let newUrl = new URL(tabs[0].url);
currentDomain = newUrl.hostname;
console.log(currentDomain);
});
});
var xhr = new XMLHttpRequest();
xhr.open("GET", "url part 1" + window.location.hostname + "url part 2", true);
xhr.responseType = 'document';
xhr.send();
xhr.onreadystatechange = function () {
console.log("XHR callback readyState = " + this.readyState);
if (this.readyState == 4) {
function getElementByXpath(path) {
return xhr.response.evaluate(path, xhr.response, null, XPathResult.STRING_TYPE, null).stringValue;
}
console.log(getElementByXpath("//div[#class='data-mini']/span/span[#class='value']/text()"));
var badgeText = getElementByXpath("//div[#class='data-mini']/span/span[#class='value']/text()");
console.log(badgeText);
chrome.browserAction.setBadgeText({ text: String(badgeText) });
console.log(String(badgeText));
}
}
With the first part i get clean domain of the currently loaded tab into console. The second part should do the rest job.
What remains, is to get
currentDomain
into
xhr.open("GET", "https://app.sistrix.com/app_visindex/__loadModule/lang/de/domain/"+currentDomain+"/source/de/ref/app_controller_efcdc3b3cab713326d8830ac95b499e454ae4e46053a5cc6/_action/_result/_cache//_loadbox/empty/_ajax/1/_module-expire/217287/_controller", true);
The main goal:
on visiting of every other domain the url in xhr.open is modified with the current domain,
XHRHttpRequest gets new number from HTML element defined with XPath,
the number is shown as BadgeText.
If I understood well your question, you want to get page information + it's current hostname when switching tabs.
So { pageInfo, currentHost }.
This information you want to pass to the background and do an XHR with the right host...
Here is how would I solve this:
In your content.js:
// Gets needed data from the content when the tab changes (i.e on window focus).
// For example I will take the content of first paragraph and the hostname:
window.onfocus = function () {
const firstParagraphText = document.getElementsByTagName('p')[0].innerText;
const hostName = window.location.host;
this.sendDataToBackground({ paragraph: firstParagraphText, host: hostName });
}
function sendDataToBackground(data) {
chrome.runtime.sendMessage(chrome.runtime.id, data);
}
Then in your background.js you have to retrieve the info sent by content:
chrome.runtime.onMessage.addListener(function (request, sender) {
console.log('First paragraph = ', request.paragraph);
console.log('Host = ', request.host);
// DO XHR WITH NEW HOST...
});
This works for me, if you wish I can create a public repo with one working example...
The correct and working code is:
chrome.tabs.onUpdated.addListener(function(tabid, changeInfo, tab){
chrome.tabs.query({'active' : true, 'currentWindow': true}, function(tabs){
let newUrl = new URL(tabs[0].url);
var currentDomain = newUrl.hostname;
var xhr = new XMLHttpRequest();
xhr.open("GET", "url part 1"+currentDomain+"url part 2", true);
xhr.responseType='document';
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
function getElementByXpath(path) {
return xhr.response.evaluate(path, xhr.response, null, XPathResult.STRING_TYPE, null).stringValue;
}
var badgeText = getElementByXpath("//div[#class='data-mini']/span/span[#class='value']/text()");
chrome.browserAction.setBadgeText({text: String(badgeText)});
chrome.browserAction.setBadgeBackgroundColor({ color: '#1d2554' });
}
}
});
});

How to stream new data to clients browser when index.html change, without the need of refreshing or reloading the web page

I am new on Html. What i need is this.
I have an index.html file on a server which is blank.
I open it and write some text inside the body all the time.
What i want is that when i save the html,
the new data to appear on my clients browser
without the need to refresh or reload the page.
I have no idea on how to do it,so i haven't try anything.
Is it possible? Is it simple?
This is a sample javascript code to read an online url and update the content container with the result.
I couldn't find a simple live update page so used my own website readme in github...
var timeout = 2000,
index = 1,
cancel = false,
url = 'https://raw.githubusercontent.com/petjofi/krivoshiev.com/master/README.md';
function update() {
updateIndex();
load(url, done);
if (!cancel) setTimeout(update, timeout);
}
function updateIndex() {
document.getElementById("index").innerHTML = index++;
}
function done(result) {
document.getElementById("content").innerHTML = result;
}
function load(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
}
<button onclick="update()">start</button>
<button onclick="cancel=true">stop</button>
<span>updating: <span id="index">0</span></span>
<div style="margin-top: 20px" id="content"></div>

Page doesn't respond to HREF until AJAX completes asynchronous fetch

I have an ajax request executing through the XMLHttpRequest() object
My AJAX method is called in this format:
var xmlhttp = new XMLHttpRequest();
$(document).ready(function () { LoadData(); });
function LoadData()
{
var parameters = "DisplayData=true";
var url = "default.aspx";
Send(url, parameters, "DisplayData");
CheckForAbort();
}
function Send(url, parameters, QueryType)
{
...
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-lencoded");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange = function (){...}
}
There is also a timer on the page which refreshes the data by making a new request through the Send(...) method in intervals of 15 seconds. Every .3 seconds and it calls an Elipsis() method that displays and "blinks" the "loading message" (if appropriate to be displayed) and checks for the abort.
var Color = "red";
function Elipsis() {
if (ResponseMessage != "")
{
if (Color == "darkred") { Color = 'red'; } else { Color = 'darkred'; }
$("#StatusResponse").css("display", "block");
$("#StatusResponse").css("color", Color);
CheckForAbort();
}
}
function CheckForAbort()
{
console.log("MenuActivted: " + MenuActivted);
if (MenuActivted)
{
xmlhttp.abort();
ResponseMessage = "Aborting Request";
MenuActivted = false;
}
}
But when the user clicks the menu bar which is an anchor tag with the HREF set to another page. The browser doesn't respond until the ajax request has completed it's fetch.
The HTML HREF is called the following way on an ASPX page:
<%#Eval("Text")%>
the Ajax Abort sets the flag that is checked in the CheckForAbort() method:
var MenuActivted = false;
function AbortAjax()
{
MenuActivted = true;
return false;
}
I am running IE 11 on Win 7. I have called an abort() method in another section of the code. which executes the xmlhttp.abort(). The response status and ready state respond (console output below) but the page still waits to respond to the HREF
Console output:
HTML1300: Navigation occurred.
File: ChangePassword.aspx
MenuActivted: true
ReadyState: 4
Status: 0
Does anyone have a solution to this problem?
[Updated **********]
I thought I had the solution but I didn't.
I commented out the set header but although it allowed my HREF to execute it was because the xhr was throwing an error and the fetch was terminating.
xmlhttp.open("POST", url, true);
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
Please read the entire post before responding.

innerHTML works in IE and Firefox, but not Chrome

The data will not display in Chrome, unless i open an IE tab in Chrome go to the site then close it back to Chrome (sorry, if that doesn't make much sense).
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
Im just starting to learn JavaScript so I really don't know much about it.
You should use some modern Javascript library. It guards you from many of those small differences between browsers. I like jQuery.
So, with jquery your code
window.onload = function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function () {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
becomes
$(document).load(function() {
var url = "http://----.freeiz.com/gbSales/sales.json";
$.get(url, {}, function(data) {
$('#sales').html(data);
});
});
Shorter, cleaner and works in all browsers!
I think you want to use:
request.onreadystatechange = function() {
instead of:
request.onload = function() {
And change the way you check the return value.
See the asynchronous request code example here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest for more details.
Just find that only the first form tag is removed so you can put an empty form () and the next one is keep in the code.

Javascript Not Executing In Dynamically Loading Content (AHAH)

I'm dynamically loading content into a div when the user clicks a link using this code:
function ahah(url, target) {
document.getElementById(target).innerHTML = 'Opening form...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.
I'm at loss, any ideas greatly appreciated!
If you are using jquery anyways, might as well try using jquery.ajax().
You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.

Categories