Simple server-side html/JS router for three apps - javascript

I'm not a javascript programmer but have a need to do very simple routing in my website's main index.htm file. Situation: We have, let's say, three main ISAPI applications, app1.dll, app2.dll and app3.dll, all hosted by the same in-house server.
These also represent three external domains, e.g., app1.com, app2.com and app3.com, all of which hit the same server and index.htm page. What I want to do in my index.htm page is to simply redirect to the appropriate server application without further user action (ie., using the same browser window).
Now, poking around I've learned that I can obtain and display the hostname with the following script:
<script>
document.getElementById("hostname").innerHTML =
"Hostname is: " + window.location.hostname + "<br/>";
</script>
Now what I want to do is something along the following (forgive any incorrect syntax):
<script>
if { hostname = "www.app1.com" {
var url = "http://www.app1.com/isapi/app1/app1.dll/";
} else {
if { hostname = "www.app2.com" {
var url = "http://www.app1.com/isapi/app1/app2.dll/";
} else {
if { hostname = "www.app3.com" {
var url = "http://www.app3.com/isapi/app1/app3.dll/";
} else {
}
}
}
"GO TO URL";
</script>
How do I encode "GO TO URL" without buttons, etc., and further user action? I believe I need a GET command, something like this:
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
return;
but I can get this to execute.
Any suggestions most welcome.

Do you just want to redirect the user to a certain url?
You can do that through the location api.
window.location = "http://stackoverflow.com"
This will redirect the user to stackoverflow.com
So in your case just do: window.location = url
And since the the window object is the global scope you can just do location = url
EDIT:
And I would also recommend you using a switch statement instead of the nested if statements. It will be alot more readable:
var url = "";
switch(hostname){
case "www.app1.com":
url = "url..."; break;
case "otherdomain":
url = "url..."; break;
default:
url = "url..."; //if none of the above ones
}
window.location = url;

Related

"How can I get the url query string parameters of a google apps script web app sandbox in javascript?

I have a webapp that has multiple pages served as templates in a sandbox. I want to pass an ID as a url parameter between pages in my webapp.
Issue 1: I don't know how from my javascript page file I can access the url parameters as when using window.location I do not get the same url that shows in the address bar.
Is there a way of getting the parameter directly from javascript or do I have to get the server to send it to javascript?
If I need to get it from the server I am worried that as the webapp is meant to have multiple users who are on different pages of the webapp how will the server know which url to send?
Sorry if what I am saying does not make sense! I include some code below to try and help explain the issue...
Code.gs code:
function doGet(e){
var param1 = e.parameters.v;
var param2 = e.parameters.id;
if(param1 == "form"){
return loadForm();
} else if(e.parameters.v == "class") {
return loadClassView();
} else {
var tmp = HtmlService.createTemplateFromFile("home");
tmp.baseUrlToSend = baseURL;
return tmp.evaluate();
}
}
javascript:
function OnLoad(){
var thisURL = window.location;
alert(thisURL);
//I hoped this would alert something along the lines of "https://script.google.com/a/macros/s/-MY-WEB-APP-ID-/dev?v=class&id=0d2f35e9-d785-4fab-a8ee-fe8933f1c159"
//But what this actually alerts is "https://n-g5aftzut - REMOVED FOR SECURITY -mmajfkwvesq-0lu-script.googleusercontent.com/userCodeAppPanel"
}
Answer:
You will need to evaluate the parameter server-side to determine which page to load. The links to the pages should be written accordingly in your HTML.
More Information:
The script URL and the page in which the content is loaded are not of the same origin. As a result, you can not use window.location to get the script URL as you will receive a googleusercontent.com address, rather than a script.google.com address.
Solutions:
The first way of doing this is simply modifying your HTML to hard-code in your URLs. Your doGet() function will look something like:
function doGet(e) {
if (!e.parameter.v || e.parameter.v == "home") {
return HtmlService.createTemplateFromFile("home").evaluate();
}
else if (e.parameter.v == "form") {
return loadForm();
}
else if (e.parameter.v == "class") {
return loadClassView();
}
}
function loadForm() {
// do some template processing here
return HtmlService.createTemplateFromFile('form').evaluate();
}
function loadClassView() {
// do some template processing here
return HtmlService.createTemplateFromFile('class').evaluate();
}
And then in your HTML you can hard-code in your links:
<a href='https://script.google.com/a/domain.com/macros/s/script-id/exec?v=class'>Click here to go to 'Class'.</a>
Alternatively, you can use your current templating and insert the script url when the doGet() function is called for the respective page:
function doGet(e) {
if (!e.parameter.v || e.parameter.v == "home") {
return HtmlService.createTemplateFromFile("home").evaluate();
}
// etc...
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
And insert it where you need in your html file:
<? var url = getScriptUrl(); ?>
<!-- more stuff -->
Click here to go to 'Class'
The scriptlet here will call the defined getScriptUrl() function in your server-side code which returns the web app url, and then append it to the beginning of the parameter in the anchor element.
References:
HTML Service: Templated HTML | Apps Script | Google Developers

Loading a .txt File into a JavaScript Variable without Selecting

I've asked this question before but did not explain it well enough so here's a better attempt:
I am making an application that will be run client-side, not server side. I have a .txt file in the directory with all of the code for the application, and I want to be able to automatically load the contents into a variable without the user needing to select anything. Thus, I do not want to use an input, but rather just have the file load itself when the .html page is opened. As an end result, I would want a String that contains the text inside the file.
I am not using any frameworks, just strictly coding in JavaScript, CSS, and HTML.
I assume that the answer to this question involves a Blob and using readAsText(), but even after reading the full documentation I'm unsure how to pass a URL into it so it can read the contents of a .txt file.
The easiest way of doing so is a XML request. This allows you to access the contents of files either asynchronously or synchronously. Please not that CORS will sometimes block this, so you may need to disable it if you are using chrome.
function getData(file) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", file, false);
//The false above means synchronously, true means asynchronously
xmlhttp.send();
return xmlhttp.responseText;
}
let myVar = getData("text.txt");
EDIT:
This code from Cors-anywhere at the beginning of the fuction can fix the cors policy
https://github.com/Rob--W/cors-anywhere/#documentation
(function() {
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = window.location.protocol + '//' + window.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
})();

By-pass virus scan for Google Drive links and get the confirm ID

With some help from this thread I came up with the code below. How can I fetch the Google Drive file ID, open the direct link to the file and snatch the virus scan confirm ID that is required to stream files over 100 MB and then puzzle back the link? I'm kind of stuck at the xhr part.
function fixGoogleDriveURL(url) {
if (url.indexOf('drive.google.com') !== -1) {
var DocIDfull = url;
var DocIDstart = DocIDfull.indexOf('open?id=');
if (DocIDstart == -1) {
// invalid
return url;
}
var DocID = DocIDfull.slice(DocIDstart+8);
url = 'https://drive.google.com/uc?export=download&id=' + DocID;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
var token = xhr.responseText.match("/confirm=([0-9A-Za-z]+)&/");
window.location.replace(url + '&confirm=' + token[1]);
// should I add url += '&confirm=' + token[1] here instead of window.location?
}
}
};
xhr.open("GET", url);
xhr.send();
}
return url;
}
console.log(fixGoogleDriveURL('https://drive.google.com/open?id=1C25uoL6nIqqNhex3wm8VwODsO2q2pXBt') + "\n<-- should output:\nhttps://drive.google.com/uc?export=download&id=1C25uoL6nIqqNhex3wm8VwODsO2q2pXBt&confirm=XXXXX");
Scraping GDrive using Client-Side JavaScript isn't explicitly allowed by Google and therefore your Ajax call/XHR fails.
The only way to get around that restriction is by using a proxy in the middle that will forward Google's Website code but add appropriate Access-Control Allow-Origin Headers.
You can either use your own server for that (some minimal server-side script code will do) or you can use a service like http://multiverso.me/AllOrigins/ or https://corsproxy.github.io/ to proxy the request for you.
The AllOrigins site has some example code for use with jQuery, but basically they work by URI encoding the URL you want to access and appending that string to the site's proxy URL.
Here's an article by freecodecamp.org that outlines how to use these services (skip to the Don’t Let CORS Stop You! section.
Note: A security advice: These services are working fine right now, but they could go out of business tomorrow and start serving malicious data instead or redirect your file requests to completely different files or completely different websites altogether. It's up to you to decide if you want to trust these strangers or not.

javascript window.open without http://

I have a small tool build with Delphi that collects url's from a file or from the clipboard, and than builds a file called test.htm with a content like this :
<!DOCTYPE html>
<html>
<body>
<p>Click the button retrieve the links....</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
window.open('http://www.speedtest.net/', '_blank');
window.open('www.speedtest.net/', '_blank');
and so on...
}
</script>
</body>
</html>
The idea is to click on the button, and then a new tab (or window) is created for every url inside myFunction.
This works, but with one small problem.
In the code example there are 2 url's, one with the http:// prefix and one without it. The first url works as expected and creates a new tab (or window) with the following url:
http://www.speedtest.net
The second 'window.open' does not work as I expected. This 'window.open' will create the following url in the new tab (or window)
file:///c:/myApplicaton/www.speedtest.net
As you have already figured out, the application is an executable in c:\myApplication
So my question(s) is, is there a way to use 'window.open' to create a new tab (or window) without putting the path of the application in front of the url ?
If this is not possible with 'window.open', is there another way to do this ?
Or is the only way to do this to have the application put the http:// in front of every url that does not have it already ?
As you suggested, the only way is to add the http protocol to each URL which is missing it. It's a pretty simple and straightforward solution with other benefits to it.
Consider this piece of code:
function windowOpen(url, name, specs) {
if (!url.match(/^https?:\/\//i)) {
url = 'http://' + url;
}
return window.open(url, name, specs);
}
What I usually do is to also add the functionality of passing specs as an object, which is much more manageable, in my opinion, than a string, even setting specs defaults if needed, and you can also automate the name creation and make the argument optional in case it's redundant to your cause.
Here's an example of how the next stage of this function may look like.
function windowOpen(url, name, specs) {
if (!url.match(/^https?:\/\//i)) {
url = 'http://' + url;
}
// name is optional
if (typeof name === 'object') {
specs = name;
name = null;
}
if (!name) {
name = 'window_' + Math.random();
}
if (typeof specs === 'object') {
for (var specs_keys = Object.keys(specs), i = 0, specs_array = [];
i < specs_keys.length; i++) {
specs_array.push(specs_keys[i] + '=' + specs[specs_keys[i]]);
}
specs = specs_array.join(',');
}
return window.open(url, name, specs);
}
I think the best way would be to add "//" + url
In this case - it isn't important, what protocol (http or https) you expect to receive as a result.
url = url.match(/^https?:/) ? url : '//' + url;
window.open(url, '_blank');
The only way to do this is to have the application put the http:// in front of every url that does not have it already.
For the behavior you're describing, you have to include your protocol with window.open. You could use a tertiary operator to simply include the protocol if it doesn't already exist:
url = url.match(/^http[s]?:\/\//) ? url : 'http://' + url;
Note that you'll need to use the SSL protocol sometimes, so this is not a complete solution.
I made small changes function form answered by iMoses which worked for me.
Check for both https OR http protocol
if (!url.match(/^http?:\/\//i) || !url.match(/^https?:\/\//i)) {
url = 'http://' + url;
}
Hope it make more accurate for other situation !

debug help with rare unexpected output in js

I have the following javascript on my page that is supposed to generate and go to a url instead of posting a form:
var tokenList = ["auto", "usate"];
var dirList = [];
function makeUrl(prov, manuf, model, price){
if (_addToken(prov)){
_joinTokens();
}
if (_addToken(manuf)){
_addToken(model);
_joinTokens();
}
if (price){
return _joinDirs() + "?prezzo=" + price;
}
return _joinDirs();
}
function _addToken(tok){
if (tok){
tokenList.push(tok.replace(/ /g,"_"));
return true;
}
return false;
}
function _joinTokens(){
dirList.push(tokenList.join('-'));
tokenList = [];
}
function _joinDirs(){
if (tokenList){
_joinTokens();
}
var url = '/' + dirList.join('/');
if (url.charAt(url.length-1) == '/'){
url = url.slice(0, -1);
}
return url;
}
It's triggered by this code:
$(document).ready(function(){
$('#navForm').submit(function() {
var prov = $("[name=select-provincia]").val();
var manuf = $("[name=select-marca]").val();
var model = $("[name=select-modello]").val();
var price = $("[name=select-prezzo]").val();
var url = makeUrl(prov, manuf, model, price);
window.location = url;
return false;
});
});
It's been a long while since I translated this code from its original python. I've been getting rare errors in my server logs occasionally that show users trying to visit strange urls that look almost like two urls concatenated. I haven't been able to ever duplicate such an error, but my best guess is that there is something going on with my javascript. The last two times I got this error I noticed that the user was using firefox 3.6 and iphone. Could this be some kind of browser incompatibility? Is there anything wrong with my javascript at all? Is the error just in userland?
For reference here is an example wrong url:
/auto-usate-pesaro_e_urbino/fiat-500//rimini/fiat-500?prezzo=13000
and two possible correct ones:
/auto-usate-pesaro_e_urbino/fiat-500?prezzo=13000
/auto-usate-rimini/fiat-500?prezzo=13000
Any unrelated suggestions for optimizing the code are welcome since I am bad at this.
Not sure it that's the case, but I think those strange URLs might be a result of appending the generated URL to the URL of the page being viewed. You are generating just the pathname part of the URL, not including the protocol and host name (http://foo.com) -- it's possible that some browsers are interpreting this path as relative to the current one. Try prepending the URL with the protocol and hostname.
You might also want to see this answer: Setting JavaScript window.location and follow the advice to write the URL to window.location.href.

Categories

Resources