javascript window.open without http:// - javascript

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 !

Related

Adding parameters to url on page load only if no paremeters already exist

I searched for the answer to my question and even tried some solutions, but wasn't able to get anything to really work. I'm newish to javascript, so that might also be why.
I have a specific URL and whenever someone goes to that URL, I want to add parameters to it, but only if no parameters are already present. Parameters get added to the URL for other on click events, but on page load, I need a set of parameters added to the URL.
I tried to use the history API and I think I'm kind of close, but I'm not able to get it to do what I want it to do.
function addDefaultParam(url) {
var currentURL = window.location.href; //get the current url
var baseURL = '/our-partners'; //this is the url that should have params added
var paramString = '?asc=true&sortBy=display_name'; //here are the params
if (currentURL === baseURL) {
window.history.pushState("object or string", "Title", "/" + paramString);
}
return url;
}
I'm using basic js in this because that's what was used in the other functions (I inherited this code). Any help would be greatly appreciated.
You can register the addDefaultParam function to fire when the document first loads in the browser and use the Location interface to check the state of the current path and query string of the URL and if they match your conditions, update the current query string value.
See below for an example:
window.addEventListener("load", addDefaultParam);
function addDefaultParam() {
let currentPath = document.location.pathname;
let currentQueryString = document.location.search;
let targetPath = "/our-partners";
if (currentPath === targetPath && !currentQueryString) {
document.location.search = "?asc=true&sortBy=display_name";
}
}

window.location not replaced but concatenated

I have this code:
$(window).ready(function() {
var url = window.location.href;
if (url.includes("#/projet/")) {
projectId = url.substring(url.indexOf("#")+1).split("/").slice(2, 3).toString();
window.location.href = "projects/" + projectId;
};
})
I'm redirected but the window.location is not replaced, just concatenated.
For instance, if my URL is localhost:3000/users/212323/dashboard, after the javascript redirection, I get localhost:3000/users/212323/projects/123456 instead of localhost:3000/projects/123456
I don't understand why the href is concatenated and not replaced, do you have an idea?
window.location.href = 'someurl' works the same way as clicking that someurl in a <a> tag.
When using a relative path (i.e. without / in the beginning), your browser will concatenate the URL to the existing URL.
Simple fix in your case is to prepend the /:
window.location.href = "/projects/" + projectId;
Note though, that this will cause the site possibly not work anymore if it is moved to another location. That is why many web frameworks use full URLs and some kind of base-url to get the linking correctly.
You need to add another / to the beginning of the url, otherwise the browser interprets the url as a relative url to the curent url.
window.location.href = "/projects/" + projectId;
The extra / at the start tells the browser to start from the root url.

Adding a string (subdomain) to the front of URL with Javascript or PHP

I've been searching but couldn't find much info on this.
Basically, I'm building a (PHP based) website, and for my own language switching implementation I need to have buttons that I can click and it would redirect to the exact same page in the selected language. For example: http://example.com/page1?param1 to http://es.example.com/page1?param1.
Is there any way to do this with javascript or php?
Thanks!
With PHP, it's easy to find the current URL:
$_SERVER['REQUEST_URI'] -> /page1?param1
$_SERVER['HTTP_HOST'] -> example.com
You can easily use this information to add links, buttons or menu to other language versions
You can get the current URL in JavaScript using:
window.location.href
So your button could call a function and pass in a value to that function. And then using a regular expression you can insert your language variable in the appropriate spot.
<button id='esLanguage' onclick="changeLanguage('es')"></button>
function changeLanguage(language) {
var url = window.location.href
var newUrl = url.replace(/^http:\/\//, 'http://' + language + '.')
windows.location = newUrl;
}
This is all assuming you have sub domains set up for each language.
Using JavaScript, you can do this:
window.location.host = `subdomain.${window.location.host}`
Be aware, this is going to reload the page.
The simplest solution for the current window.location:
function withSubdomain(path = window.location.pathname, subdomain = 'blog') {
const { protocol, host } = window.location;
return `${protocol}//${subdomain}.${host}${path}`;
}
Try this.you should include your subdomain path in href then click the link it will auto redirect to the page.
param1
param2
param3
param4
param5
.
.
.
..
Note:*
each link is the new html pages

Get current URL and modify subdirectory and then go to URL with Javascript

I'm creating a bilingual website for a client. Two versions of the site in different languages will be created and stored in two folders:
/en/
/chi/
What I want to do is create a link to toggle between the two languages. On the conceptual level, I understand that Javascript can detect the current URL and split it into its different components, modify parts of it (in this case change between /en/ and /chi/), and then go to that new URL when the link is clicked.
But I have zero knowledge in javascript so I have no idea how to execute... I have come across this page:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
but it doesn't explain how to modify and go to the new link.
You help will be greatly appreciated!!
To not break usability considerations like Shift + Click to open in a new window, you should create a plain old link (<a>) that points to the other language URL. There's nothing wrong with building the link via JavaScript, but you could also do it on the server using PHP or whatever templating language you're using.
Here's a script that does this with JavaScript if that's what you decide you'd like to do.
<!DOCTYPE html>
<body>
Content before the link.
<script>
(function () {
// this assumes you're on the en version and want to switch to chi
var holder = document.createElement("div");
var url = window.location.href.replace("/en/", "/chi/");
var link = document.createElement("a");
link.innerText = "Chewa"; // or whatever the link should be
link.href = url;
holder.appendChild(link);
document.write(holder.innerHTML);
})();
</script>
Content after the link.
</body>
If you simply want to take the full URL and replace /en/ with /chi/ or vise-versa, use the code below.
HTML
<span onclick="SwitchLang()">View [Some other Language]</span>
JavaScript
function SwitchLang() {
//Does URL contain "/en/"?
if(window.location.href.indexOf("/en/") != -1) {
//URL contain "/en/", replace with "/chi/"
window.location.href = window.location.href.replace("/en/", "/chi/");
}
//Does URL contain "/chi/"?
else if(window.location.href.indexOf("/chi/") != -1) {
//URL contain "/chi/", replace with "/en/"
window.location.href = window.location.href.replace("/chi/", "/en/");
}
}
Or, a bit more concise (un-commented version)
function SwitchLang() {
if(window.location.href.indexOf("/en/") != -1)
window.location.href = window.location.href.replace("/en/", "/chi/");
else if(window.location.href.indexOf("/chi/") != -1)
window.location.href = window.location.href.replace("/chi/", "/en/");
}
Note: In JS, when you modify window.location.href, the new URL is automatically loaded.
Here's a working fiddle for you to play with.
It looks like you need to change the window.location.pathname. For example:
// assuming the url `http://www.example.org/en/foo/bar/page.html`
var paths = window.location.pathname.split("/");
// change `en`
paths[1] = "chi";
// go to the new url
window.location.pathname = paths.join("/");
See:
https://developer.mozilla.org/en/DOM/window.location

Fetch and Replace href attribute value of <a> tag using prototype

I have a simple link inside my tml (apache tapestry specific) :
www.google.com
Now on the browser if I am trying to click the link, actually it's redirecting to
http://localhost:8080/..../..../www.google.com
Instead of it should open a new tab for that link.
So the logic which I am thinking is :
1) Fire a javascript on page load
2) Get the href value of anchor tag
3) Append http:// at the start, if it doesn't contains it.
So to do this, actually I want to use prototype (javascript framework), and I am bit new to this...
How can I write the function using the Prototype.js library?
You don't say where the value for your href is coming from. As you say you need to prepend an "http". Assuming the link is dynamically rendered, why don't you just do this server-side, probably much easier. In tml:
... href="${url}" ....
and in .java:
public String getUrl() {
return "http://" + url;
}
This is a much better approach than doing it client-side as what happens if the user has javascript turned off?
On the other hand, if it's a static link in your .tml, just write "http://www.google.com"!
Edit: In light of your comment below:
public String getUrl() {
if (!url.startsWith("http://") {
url = "http://" + url;
}
return url;
}
The above is just an example of what do do. You can either add another method to activityDetails which does this (e.g getExternalLinkWithProtocol()), or provide a wrapper method similar to the one above.
No reason to do this on the client side. Simply change your template to:
www.google.com
and if it's based on a property:
${hostname}
... adjust to fit your properties, etc.
window.onload = function(){
var links = document.links;
for(var i=links.length-1; i>=0; i--){
var link = links[i];
var href = link.getAttribute("href");
if(href.indexOf("http://") < 0){
link.href = "http://" + href;
}
}
};

Categories

Resources