Add referrer URL to end of new URL - javascript

I have the following code. I store the URL, then direct to a new URL, and I want the current URL to be at the end of it (following "?url="). However, the code just produces infinite redirects.
var currentURL = window.location.href;
for(var i = 0; i < targetURLs.length; i++)
if(currentURL.toString().indexOf(targetURLs[i]) >= 0) {
window.stop();
window.location.href = 'https://example.com?url=' +
currentURL.toString();
}

Related

How to route API requests through certain IP address?

On a remote server, there is an HTML page with javascript. The user visits this page, makes some settings, and runs an API query.
How can I ensure that all API queries are routed independently from the user's location through a specific IP address, which is my proxy gateway? How is it possible with javascript?
This is the whole function that runs API query:
function Query(keyword)
{
var qk = keyword;
var queryresult = '';
queryflag = true;
$.ajax({
url: window.location.protocol + "//apiv3.example.com/lookup",
jsonp: "jsonp",
dataType: "jsonp",
data: {
q: qk,
client: "chrome",
hl: document.querySelector("select").value
},
success: function(res) {
var rL = res[1];
var i = 0;
for(i = 0; i < rL.length; i++)
{
var currents = CleanVal(rL[i]);
if(hashMapResults[currents] != 1)
{
hashMapResults[currents] = 1;
SaveLatest(CleanVal(rL[i]));
ktq[ktq.length] = currents;
var j = 0;
for(j = 0; j < 26; j++)
{
var chr = String.fromCharCode(97 + j);
var currentx = currents + ' ' + chr;
ktq[ktq.length] = currentx;
hashMapResults[currentx] = 1;
}
}
}
FilterAndDisplay();
var textarea = document.getElementById("input");
textarea.scrollTop = textarea.scrollHeight;
queryflag = false;
}
});
}
You can't control routing between the user and the endpoint.
If you want data to go through your server then the URL you pass to $.ajax needs to be that of your server.

Chrome Extension - Rerun extension script after redirecting current tab

I am trying to develop a chrome extension which parses data from the current tab and post it to a url which does processing on the data. In certain cases the page may need to be redirected so that certain get parameters are present. My popup.js can successfully do the redirect, but I need to click on the extension a second time to get it to run properly. Note: it runs properly if the page has the correct parameters. How can I adjust this so that the code reruns after the redirect and posts the new source to the specified url.
Here is my popup.js:
var url = "";
chrome.runtime.onMessage.addListener(function(request, sender) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
url = tabs[0].url;
if (url.search("[?&]view=list") == -1)
{
url = setGetParameter(url,'view','list');
chrome.tabs.update(tabs[0].id,{url:url});
process(request);
}
});
process(request);
});
function process(request) {
if (request.action == "getSource") {
message.innerText = request.source;
var data = new FormData();
data.append('source',request.source);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE) {
message.innerText = xhttp.responseText;
}
}
xhttp.open("POST","http://127.0.0.1:5000/api/scraper",true);
xhttp.send(data);
}
}
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
function setGetParameter(url, paramName, paramValue)
{
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
return url + hash;
}
window.onload = onWindowLoad;
Take a look at webRequest.onBeforeRedirect, this event fired when a redirect is about to be executed. You can listen to this event and do your logic again.
Don't forget to declare webRequest permission along with host permissions for any hosts whose network requests you want to access in you manifest.json.

How to check URL format

I want to check whether the url format is #Url.Content("~/Dashboard/Index?studentId="). If it is, we have to set #Url.Content("~/Dashboard/Index"), if not window.location.href. How to do it?
var currentUrl = (#Url.Content("~/Dashboard/Index?studentId=")) ? (#Url.Content("~/Dashboard/Index")) : window.location.href;
if (currentUrl.indexOf('#') > -1) {
currentUrl = currentUrl.replace('#', '');
}
else {
currentUrl += '#';
}
window.location.href = currentUrl;

Equivalent function in Javascript from jQuery

$.ajax({
url: 'http://' + window.location.host + '/',
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});
I couldn't find a way to do the same in javascript, I can make ajax call like this
request = new XMLHttpRequest();
request.open('GET', 'http://' + window.location.host + '/', true);
request.onload = function(files) {
if (request.status >= 200 && request.status < 400){
// Success!
resp = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
but how do I get the list of the files in the directory?
CSJS and/or SSJS both answers are okay.
My main goal is not to use jQuery to accomplish what I want.
If you want to loop through the a:contains(.jpg) like in your jQuery example, your best bet is probably to use a DocumentFragment and then call .querySelectorAll on it :
var div = document.createElement('div');
div.innerHTML = request.responseText;
// if you want to search using text
var links = div.querySelectorAll('a')
for (i = 0; i < links.length; i++) {
var link = links[i];
if (!~link.innerHTML.indexOf('.jpg'))
continue;
// found one !
}
// if you want to search using an attribute
var links = div.querySelectorAll("a[href*='.jpg']");
You can dump the response text into a newly created <div> and use the standard methods to access the anchors; the following should even work for IE7:
// $(resp)
var doc = document.createElement('div');
doc.innerHTML = resp;
// .find('a')
var anchors = doc.getElementsByTagName('a'), // get all anchors
container = document.getElementById('some_id');
// .filter(":contains(.jpg)")
for (var i = 0; i < anchors.length; ++i) {
var contents = anchors[i].textContent || anchors[i].innerText || '';
if (contents.indexOf('.jpg') != -1) {
// var images = $(this).attr("href");
// $('<p></p>').html(images).appendTo
var para = document.createElement('p'),
text = document.createTextNode(anchors[i].href);
para.appendChild(text);
container.appendChild(para);
}
}

Difficulty in loading multiple images in a list view served by multiple xml files

I am developing a html application for Android and I am trying to load images in a list view. Data specific to list items is being served by multiple xml files. I am using ajax to load xml files and populate the list items. Problem I am facing here is that there are 164 list items. Hence, 164 images and 10 xml files to load. my loader function exhausts after two iterations. It does read the xml files but it's unable to dynamically create list items and populate them with images after two iterations. I believe it's due to stack limitations. I can't think of alternate solution. If somebody could suggest an alternate solution that will be highly appreciated. Below is my loader function. It's a recursive function:
function loadChannels() {
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){ console.log('Error Loading Channel XML'); },
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
loadChannels();
}
}
});
}
try to remove the recursion with an outer loop - something like that:
function loadChannels(){
var stopFlag = false;
// request the pages one after another till done
while(!stopFlag)
{
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){
console.log('Error Loading Channel XML');
errorFlaf = true;
},
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
// lets disable the recursion
// loadChannels();
}
else {
stopFlag = true;
}
}
});
}
}

Categories