Jquery Redirect Based on URL location - javascript

This is what I'm trying to solve for...
Only if the URL explicitly contains /foldername/index.htm && /foldername/ on mydomain.com then redirect to http://www.example.com
Should the URL contain any URL parameter /foldername/index.htm?example it should not redirect
All other URLs should not redirect
This is my javascript which is incomplete, but is ultimately what I'm trying to solve for...
var locaz=""+window.location;
if (locaz.indexOf("mydomain.com") >= 0) {
var relLoc = [
["/foldername/index.htm"],
["/foldername/"]
];
window.location = "http://www.example.com";
}
This is for the purpose to manage a URL that some users are hitting based on a particular way like a bookmark. Without removing the page, we want to monitor how many people are hitting the page before we take further action.

Won't the page always be on the same domain, also if the url contains /foldername/pagename.htm won't it also already include /foldername? So an && check there would be redundant.
Try the below code.
var path = window.location.pathname;
if ( (path === '/foldername' || path === '/foldername/index.html') && !window.location.search ) {
alert('should redirect');
} else {
alert('should not redirect');
}

var url = window.location;
var regexDomain = /mydomain\.com\/[a-zA-Z0-9_\-]*\/[a-zA-Z0-9_\-]*[\/\.a-z]*$/
if(regexDomain.test(url)) {
window.location = "http://www.example.com";
}

Familiarize with the location object. It provides pathname, search and hostname as attributes, sparing you the RegExp hassle (you'd most like get wrong anyways). You're looking for something along the lines of:
// no redirect if there is a query string
var redirect = !window.location.search
// only redirect if this is run on mydomain.com or on of its sub-domains
&& window.location.hostname.match(/(?:^|\.)mydomain\.com$/)
// only redirect if path is /foldername/ or /foldername/index.html
&& (window.location.pathname === '/foldername/' || window.location.pathname === '/foldername/index.html');
if (redirect) {
alert('boom');
}

Related

In vanilla JavaScript, turn relative path + base URL into absolute URL

In Ruby, it’s simple to do this, but in JavaScript, I’m not sure.
Given a starting page, such as http://example.org/foo/bar, I want to be able to take any link on the page, which can have any sort of href such as /x.php, ?p=3, y.html, etc., and turn it into a fully qualified absolute URL, such as (in the last example) http://example.org/foo/y.html.
Is there any sort of simple way to do this? If it helps, we can assume these paths do live in an actual web page as actual <a href> elements.
The URL constructor takes a second, base argument, which does exactly what you want:
const base = 'http://example.org/foo/bar';
[ '/x.php',
'?p=3',
'y.html'
].forEach(urlPart => {
const url = new URL(urlPart, base);
console.log(url.href);
});
.as-console-wrapper{min-height:100%}
<script src="//rawgit.com/github/url-polyfill/0.5.6/url.js"></script>
The URL API works in all major browsers except IE. If you need to support IE, there are polyfills available. Node.js also has it built in (const { URL } = require('url');).
If your baseURL is equal to the current page, try this:
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
};
})();
Found here: https://davidwalsh.name/get-absolute-url
Tried it and it worked well for relative as well as absolute URLs (it makes them all absolute) - assuming your basePath is actually your own page.
Use this script (but test it first for the various cases, I just wrote it and wouldn't guarantee I haven't overlooked any case). Note that if the path of the URL specifies a directory and not a file, it always ends in a /, even though the browser might not show that.
var getAbsoluteURL = function (url, href) {
var path = url.split(/[#?]/)[0];
var basePath = path.slice(0, path.lastIndexOf('/'));
var domain = url.split('/').slice(0,3).join('/');
var protocol = url.split('/')[0];
switch (href.charAt(0)) {
case '/':
{
if (href.length > 1 && href.charAt(1) == '/')
return protocol + href;
else
return domain + href;
}
case '#':
case '?':
return path + href;
default:
return basePath + '/' + href;
}
}

Clickjacking remediation via domain name comparison

I'm working on hardening our application to cross frame scripting/clickjacking attacks. Our application is hosted under multiple, different parent sites within an iframe. Each of these parent sites shares the same high level domain name (ex. *.foo.com). I would like be able to ensure that the parent, framing site is always the same as our application domain. For example:
Parent sites: apple.foo.com, pear.foo.com, banana.foo.com
Our site: mysite.foo.com
I know I can do something like this via Javascript but I would prefer not to embed our domain name within the code for portability reasons.
<script type="text/javascript">
var topFrameHostname = "";
try
{
topFrameHostname = top.location.hostname;
}
catch (err)
{
topFrameHostname = "";
}
if (self !== top && document.referrer.match(/^https?:\/\/([^\/]+\.)?foo\.com(\/|$)/i)) == null &&
topFrameHostname != self.location.hostname)
{
top.location = self.location;
}
else
{
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
}
</script>
So my question is can I use regular expressions to compare the domain name from the top.location and self.location values? This way I would be able to ensure it is always only a parent site from the same high level domain framing our application. Looking for a little help with the regular expression coding. Is this approach sound?
why does anyone think that regex is the one and only magic bullet when talking about matching anything?
How about this:
function domain(url){
if(typeof url === "string") url = new URL(url); //sugar, to handle strings
return url.hostname.split('.').slice(-2).join('.').toLowerCase();
}
domain(top.location) === domain(self.location)
I had to remove the reference to top.location and use document.referrer instead in order avoid the permissions error. Also, the URL function will not work in IE so I just used string functions to extract and compare the URLs:
<style id="antiClickjack">body{display:none !important;}</style>
<script type="text/javascript">
var topFrameHostname = "";
var ref = document.referrer;
var tophld = ref.split("/")[2].split(".").slice(1).join(".");
var selfhld = self.location.hostname.split(".").slice(1).join(".");
try
{
topFrameHostname = top.location.hostname;
}
catch (err)
{
topFrameHostname = "";
}
if (self !== top && tophld !== selfhld &&
topFrameHostname != self.location.hostname)
{
top.location = self.location;
}
else
{
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
}
</script>
This seems to be doing the trick and passing the clickjack.html test page.

How to store a clicked URL as a variable to use in an if statement?

Here is my issue. I want window.open(TargetLink1[0].href); to only be activated if the element alertboxHeader does not exist, TargetLink1 is true and on only the page that was opened when I clicked a link. I have successfully done the first two and the issue is with getting, storing or checking for the right url, I don't know where the issue is. This is my code. The URL clicked would as have to be able to be changed if a new URL is clicked.
var varurl;
var TargetLink1 = $("a:contains('Accept')")
if ((!document.getElementById('alertboxHeader') && (TargetLink1.length) && (window.location.href.indexOf("" + varurl + "") > -1) )) {
window.open(TargetLink1[0].href);
}
function storeurl() {
var varurl = document.URL;
}
document.onclick = storeurl;
I think what you want is something like:
var validSource = (document.referrer !== "") ? (document.location.href.indexOf(document.referrer) == 0) : false;
But be aware that the above compares the document.referrer URL to the current URL as two strings, so that if your referrer were:
http://example.org?q=test
and the current URL (the link they followed) is:
http://example.org/1
it would handle it as not matching because of the query string in the referrer URL.
Here's a better way to handle it, using the URL object prototype (which is not necessarily supported in all browsers, but works in Chrome and FF):
var referrerOrigin = new URL(document.referrer).origin;
var currentOrigin = document.location.origin;
var validSource = ( referrerOrigin == currentOrigin );
The problem is here: document.onclick = storeurl; You should give any id from the document.For Example:
document.getElementById("IdHere").onclick = storeurl;

Javascript regular expression to add protocol to url string

I have an application to list some website details using JavaScript. There will be a link to website which is generated using JavaScript itself. Sometimes I will get my link as,
Website
But sometimes it will be,
Website
In the second time the link is not working, there is no protocol.
So I am looking for a JavaScript regular expression function to add http:// if there in no protocol.
My code looks like,
var website_link = document.createElement("a");
website_link.innerHTML = "Website";
website_link.href = my_JSON_object.website;
website_link.target = "_blank";
profile.appendChild(website_link);
And no local links will come.
See this link.
function setHttp(link) {
if (link.search(/^http[s]?\:\/\//) == -1) {
link = 'http://' + link;
}
return link;
}
alert(setHttp("www.google.com"));
alert(setHttp("http://www.google.com/"));
In your code it will be like:
var website_link = document.createElement("a");
website_link.innerHTML = "Website";
if (my_JSON_object.website.search(/^http[s]?\:\/\//) == -1) {
my_JSON_object.website = 'http://' + my_JSON_object.website;
}
website_link.href = my_JSON_object.website;
website_link.target = "_blank";
profile.appendChild(website_link);
For example, using negative lookahead:
your_string.replace(/href="(?!http)/, 'href="http://');
Example:
> 'Website'.replace(/href="(?!http)/, 'href="http://');
"Website"
> 'Website'.replace(/href="(?!http)/, 'href="http://');
"Website"
I've wrapped this functionality into the NPM module url-schemify:
var schemify = require('url-schemify');
var assert = require('assert');
// url-schemify adds default scheme (http) to the URLs that miss it
assert.equal(schemify('google.com'), 'http://google.com');
assert.equal(schemify('www.example.com'), 'http://www.example.com');
// default scheme could be configured through the options parameter
assert.equal(schemify('google.com', { scheme: 'https' }), 'https://google.com');
// { scheme: '' } will produce protocol-related URL
assert.equal(schemify('www.example.com', { scheme: '' }), '//www.example.com');
// url-schemify doesn't modify URLs that already have scheme or protocol-related ones:
assert.equal(schemify('http://google.com'), 'http://google.com');
assert.equal(schemify('https://www.example.com'), 'https://www.example.com');
assert.equal(schemify('ftp://example.com'), 'ftp://example.com');
assert.equal(schemify('//example.com'), '//example.com');

Finding previous URL from window.history

I've hosts file blocking so time to time, I get these "Page not found" errors browsing thru deals.
Since I got tired of copying the target url, unescaping, replacing it in address bar and hitting enter, I wrote a handy bookmarklet to automate this:
(function () {
var href = window.location.href;
var loc = href.indexOf('url=');
if (loc > 0) {
var endLoc = href.indexOf('&', loc + 4);
endLoc = endLoc > 0 ? endLoc : href.length;
window.location.href = unescape(href.substring(loc + 4, endLoc));
}
})()
Now the problem is that Chrome, internally redirects and unreachable page to its own bounce.php which produces the following error page.
Since it supports history API, the URL in browser address bar doesn't change, as evident from the following data:
> JSON.stringify(window.history)
{"state":null,"length":2}
Now the problem is, my bookmarklet doesn't work since window.location.href points to "data:text/html,chromewebdata" once this happens.
I've looked at this question How do you get the previous url in Javascript? whose accepted answer is blissfully incorrect. Rightfully so, document.referrer is empty in my case.
So is there a way to find the previous URL from window.history? window.history.previous is non-standard and doesn't work on Chrome anyway.
Found a way (at least while it lasts!)
Chrome sets the entire URL in document.title, so querying it is all that's needed. Here's the modified code if anyone's interested:
(function () {
var href = document.title;
var loc = href.lastIndexOf('http');
if (loc > 0) {
var endLoc = href.indexOf(' is not available', loc);
endLoc = endLoc > 0 ? endLoc : href.length;
window.location.href = unescape(unescape(href.substring(loc, endLoc)))
}
})()
Note: The double unescape is needed for links coming via Google Ads.

Categories

Resources