How to get Request.ApplicationPath in jQuery - javascript

On my razor view, I am wanting to put all of my jQuery into a separate JS file and then reference that file on the view with #Scripts.Render.
On my view, I have a section jQuery that looks like this:
var settings = {};
settings.baseUri = '#Request.ApplicationPath';
var submissionUrl = "";
if (settings.baseUri === "/ProjectNameOnServer") {
submissionUrl = settings.baseUri + "/api/apiControllerName/apiControllerMethodName/";
} else {
submissionUrl = settings.baseUri + "api/apiControllerName/apiControllerMethodName/";
}
This section of code allows me to test submitting forms with api on both my localhost and live on the server without me having to change the url.
If I am testing on my localhost, then #Request.ApplicationPath == /, but if I test on my server then #Request.ApplicationPath == /ProjectNameOnServer.
I was wondering how I could achieve getting these same values but without the use of Razor, and instead only with jQuery.
I have tried:
var settings = {};
settings.baseUri = window.location.protocol + "//" + window.location.host;
but then settings.baseUri == http://localhost:xxxxx. I just need exactly what #Request.ApplicationPath is giving me.

Use location.host to conditionally create relative path
settings.baseUri = location.host.includes('localhost') ? '/' : '/ProjectNameOnServer';

Related

Reuse javascript code on client side (node.js, express)

I'm still new to Node.js, but I'll try to explain my problem as good as I can.
So I'm working on a movie site to practice my node.js/express skills a bit and I use the following elements (img) on basically every page of my website:
Header with stats and search input and a navigation bar (will be reused on every page)
The follow JS-code are two examples of actions on the client side that I use to navigate to other web pages, this then activates GET on the client side.
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
I want this to be the same code on every page. I could type the same code every time, but that would be a waste of time.For HTML and CSS I am able to use templates (HTML) or import other CSS files to save time. Is there something similar for JS on the client side?
Put that code in a file, for example "navigator.js" and then load it in your html header in every page you want to use it
navigator.js:
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
index.html
<script src="navigator.js"></script>
Finally i suggest you to assign an id to your button, for example "searchButton" instead only "button"
Hope this helps

window.location.replace() not working [duplicate]

I want to navigate to a URL on my site. This is what I have:
var TheDemoURL = window.location.host;
if (SomeCondition1) { TheDemoURL = TheDemoURL + '/fr/demo'; }
if (SomeCondition2) { TheDemoURL = TheDemoURL + '/de/demo'; }
...
window.location.replace(TheDemoURL);
Initially, in the variable watch, I have TheDemoURL: "localhost:49173" and when I alert the final TheDemoURL is looks a good URL but in reality nothing happens.
Why is this not working?
Ok, for those who come here, the solution was to add this:
var TheDemoURL = window.location.protocol + '//' + window.location.host;
Not sure if this is specific to asp.net but it made it work.
Try using
self.location = TheDemoURL;
This will take into account iframes and other weirdness.

Unable to receive parameter in query string when redirected to other page

Hi I am developing one application in java-script. I have two pages default.aspx and addnewitem.aspx. there is one html table in default.aspx and one button. When i click on button i want to redirect to addnewitem.aspx page. I have some parameters to send in query string. I am able to redirect to addnewitem.aspx but page not found error i am getting. I am not sure why i am getting page not found error. I am trying as below.
function getValues() {
var Title = "dfd";
var PrimarySkills = "fdfd";
var SecondarySkills = "dfdf";
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=" + encodeURIComponent($(Title)) + "&PrimarySkills=" + encodeURIComponent($(PrimarySkills)) + "&SecondarySkills=" + encodeURIComponent($(SecondarySkills));
window.location.href = url;
}
I am checking querystring in addnewitem.aspx as below.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["Title"] != null && queryString["PrimarySkills"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Title:</b> " + queryString["Title"] + " <b>PrimarySkills:</b> " + queryString["PrimarySkills"] + " <b>SecondarySkills:</b> " + queryString["SecondarySkills"];
$("#lblData").html(data);
alert(data);
}
});
</script>
"http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=%5Bobject%20Object%5D&PrimarySkills=%5Bobject%20Object%5D&SecondarySkills=%5Bobject%20Object%5D"
I tried lot to fix this. May i know where i am doing wrong? Thanks for your help.
You should use the relative path in your url instead of hard coding the entire folder structure, which is probably incorrect since you are getting a 404. And you need to change the url every time you publish the site to the hosting enviroment when you hard code it like that.
So change
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=...
into
var url = "/AddNewItem.aspx?Title=...
if both the pages are in the same folder. Should AddNewItem.aspx be located in the Pages folder, you have to add that folder of course: var url = "/Pages/AddNewItem.aspx?Title=...

How to Use 1 file for different Action?

I have 2 files, there are Index.aspx and AdminHome.aspx. and also have javascript file (test.js) for logic behind.
Index and adminHome is actually same but the different is only the redirect action.
If I run program from Index.aspx then i'll be redirect to CheckSeat.aspx
If I run program from AdminHome.aspx then I'll be redirect to AdminCheckSeat.aspx. I want to use same Javascript because each file has same logic. only the redirect file is the different.
this is my redirect code on .js
var url = "CheckSeat.aspx?noSeat=" + encodeURIComponent(lObjSeat[0].Name) + "&endtime=" + encodeURIComponent(time);
window.location.replace(url);
so Is it possible to do ?
if ya, How do you do ?
example URL : http://localhost90909/abcd/index.aspx
I need 'index.aspx' segment only
You may replace the url based on current page.
if (document.URL = 'Index.aspx') {
var url = "CheckSeat.aspx?noSeat=" + encodeURIComponent(lObjSeat[0].Name) + "&endtime=" + encodeURIComponent(time);
window.location.replace(url);
}
else if (document.URL = 'AdminHome.aspx') {
var url = "AdminCheckSeat.aspx"
window.location.replace(url);
}

How to save the current webpage with casperjs/phantomjs?

Is there a way to save the current webpage by using casperjs or phantomjs?
I tried to get the html and save it into a file. But the resulting file was a lot different from the screenshot of that time (with casper.capture). Is there a way to save the current webpage?
Andrey Borisko suggested to use the disk cache to retrieve the resources. My solution is not that efficient, but you don't need to decompress text files.
I use XMLHttpRequest to retrieve all resources after I registered them with the resource.received event handler. I then filter the resources into images, css and fonts. The current limitation is that remote resource paths that contain something like ../ or ./ are not handled correctly.
I retrieve the current page content with getHTML and iterate over all captured resources to replace the path used in the markup, that is identified by a portion of the complete resource URL, with a randomly generated file name. The file extension is created from the content type of the resource. It is converted using mimeType from this gist.
Since CSS files may contain background images or fonts, they have to be processed before saving to disk. The provided loadResource function loads the resource, but does not save it.
Since XMLHttpRequest to download the resources the script has to be invoked with the --web-security=false flag:
casperjs script.js --web-security=false
script.js
var casper = require("casper").create();
var utils = require('utils');
var fs = require('fs');
var mimetype = require('./mimetype'); // URL provided below
var cssResources = [];
var imgResources = [];
var fontResources = [];
var resourceDirectory = "resources";
var debug = false;
fs.removeTree(resourceDirectory);
casper.on("remote.message", function(msg){
this.echo("remote.msg: " + msg);
});
casper.on("resource.error", function(resourceError){
this.echo("res.err: " + JSON.stringify(resourceError));
});
casper.on("page.error", function(pageError){
this.echo("page.err: " + JSON.stringify(pageError));
});
casper.on("downloaded.file", function(targetPath){
if (debug) this.echo("dl.file: " + targetPath);
});
casper.on("resource.received", function(resource){
// don't try to download data:* URI and only use stage == "end"
if (resource.url.indexOf("data:") != 0 && resource.stage == "end") {
if (resource.contentType == "text/css") {
cssResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("image/") == 0) {
imgResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("application/x-font-") == 0) {
fontResources.push({obj: resource, file: false});
}
}
});
// based on http://docs.casperjs.org/en/latest/modules/casper.html#download
casper.loadResource = function loadResource(url, method, data) {
"use strict";
this.checkStarted();
var cu = require('clientutils').create(utils.mergeObjects({}, this.options));
return cu.decode(this.base64encode(url, method, data));
};
function escapeRegExp(string) {
// from https://stackoverflow.com/a/1144788/1816580
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(find, replace, str) {
// from https://stackoverflow.com/a/1144788/1816580
return str.replace(find, replace);
}
var wrapFunctions = [
function wrapQuot1(s){
return '"' + s + '"';
},
function wrapQuot2(s){
return "'" + s + "'";
},
function csswrap(s){
return '(' + s + ')';
}
];
function findAndReplace(doc, resources, resourcesReplacer) {
// change page on the fly
resources.forEach(function(resource){
var url = resource.obj.url;
// don't download again
if (!resource.file) {
// set random filename and download it **or** call further processing which in turn will load ans write to disk
resource.file = resourceDirectory+"/"+Math.random().toString(36).slice(2)+"."+mimetype.ext[resource.obj.contentType];
if (typeof resourcesReplacer != "function") {
if (debug) casper.echo("download resource (" + resource.obj.contentType + "): " + url + " to " + resource.file);
casper.download(url, resource.file, "GET");
} else {
resourcesReplacer(resource);
}
}
wrapFunctions.forEach(function(wrap){
// test the resource url (growing from the back) with a string in the document
var lastURL;
var lastRegExp;
var subURL;
// min length is 4 characters
for(var i = 0; i < url.length-5; i++) {
subURL = url.substring(i);
lastRegExp = new RegExp(escapeRegExp(wrap(subURL)), "g");
if (doc.match(lastRegExp)) {
lastURL = subURL;
break;
}
}
if (lastURL) {
if (debug) casper.echo("replace " + lastURL + " with " + resource.file);
doc = replaceAll(lastRegExp, wrap(resource.file), doc);
}
});
});
return doc;
}
function capturePage(){
// remove all <script> and <base> tags
this.evaluate(function(){
Array.prototype.forEach.call(document.querySelectorAll("script"), function(scr){
scr.parentNode.removeChild(scr);
});
Array.prototype.forEach.call(document.querySelectorAll("base"), function(scr){
scr.parentNode.removeChild(scr);
});
});
// TODO: remove all event handlers in html
var page = this.getHTML();
page = findAndReplace(page, imgResources);
page = findAndReplace(page, cssResources, function(cssResource){
var css = casper.loadResource(cssResource.obj.url, "GET");
css = findAndReplace(css, imgResources);
css = findAndReplace(css, fontResources);
fs.write(cssResource.file, css, "wb");
});
fs.write("page.html", page, "wb");
}
casper.start("http://www.themarysue.com/").wait(3000).then(capturePage).run(function(){
this.echo("DONE");
this.exit();
});
The magic happens in findAndReplace. capturePage is completely synchronous so it can be dropped anywhere without much head ache.
URL for mimetype.js
No, I don't think there is an easy way to do this as phantomjs doesn't support rendering pages in mht format (Render as a .mht file #10117). I believe that's what you wanted.
So, it needs some work to accomplish this. I did something similar, but i was doing it the other way around I had a rendered html code that I was rendering into image/pdf through phantomjs. I had to clean the file first and it worked fine for me.
So, what I think you need to do is:
strip all js calls, like script tags or onload attributes, etc..
if you have access from local to the resources like css, images and so on (and you don't need authentication to that domain where you grab the page) than you need to change relative paths of src attributes to absolute to load images/etc.
if you don't have access to the resources when you open the page then I think you need to implement similar script to download those resources at the time phantomjs loads the page and then redirect src attributes to that folder or maybe use data uri.
You might need to change links in css files as well.
This will bring up the images\fonts and styling you are missing currently.
I'm sure there are more points. I'll update the answer if you need more info, once I see my code.

Categories

Resources