capture url in href tag - javascript

I have an exit page that informs users that they are leaving my site. How do I capture the intended url from the referring page and send the user to it once they've acknowledged on the exit page that they're aware they're leaving my site and wish to continue to their destination? My current setup works with an absolute link but not with a relative path.
this works:
href="http://acme.com/company/brand/leaving/?url=http://www.about.info/choices/
this doesn't:
href="../COMPANY/BRAND/leaving/?url=http://www.about.info/choices/"
the continue button triggers the following function:
function gbye(){
var url = window.location.toString();
var url_arr= url.split("?url=");
if(url_arr.length>1)
{
try
{
window.location = url_arr[1];
}
catch (e)
{
}
}
return false;
}
can anyone explain why the href with the relative path doesn't work (returns a directory list) and how I can make the relative path work?

Most servers are running under a Linux environment, where the filesystem is case-sensitive, ie file names with different cases are treated different.
If the first link worked correctly, use ../company/brand/leaving/?url=.... I recommend using a / (absolute root) instead of ../, because you won't have to edit your files when you move the files to a different directory, when using /.

Related

How to disable direct access to Iframe

Let's say normally my users access our web page via https://www.mycompany.com/go/mybusinessname
Inside this web page, we have a iframe which actually comes from https://www.mycompany.com/myapp
Everything is working fine, except that if for some reason, the users come to know about this url https://www.mycompany.com/myapp. They can start accessing it directly by typing into the address bar.
This is what I want to prevent them from doing. Is there any best practice to achieve this?
==== Update to provide more background ====
The parent page which is https://www.mycompany.com is the company's page and it's maintained by some other team. So they have all the generic header and footer, etc. so each application is rendered as an iframe inside it. (This also means we cannot change the parent page's code)
If users access https://www.mycompany.com/myapp directly, they won't be able to see the header and footer. Yes, it's not a big deal, but I just want to maintain the consistency.
Another of my concern is that, in our dev environment (aka when running the page locally) we don't have the parent-iframe thing. We access our page directly from http://localhost:port. Hence I want to find a solution that can allow us access it normally when running locally as well.
If such solution simple does not exist, please let me know as well :)
On your iframe's source, you can check the parent's window by using window.top.location and see if it's set to 'https://www.mycompany.com/go/mybusinessname'. If not, redirect the page.
var myUrl = 'https://www.mycompany.com/go/mybusinessname';
if(window.top.location.href !== myUrl) {
window.top.location.href = myUrl;
}
I realized we already had a function to determine whether the page in running under https://www.mycompany.com. So now I only need to do the below to perform the redirecting when our page is not iframe
var expectedPathname = "/go/mybusinessname";
var getLocation = function (href) {
var l = document.createElement("a");
l.href = href;
return l;
};
if (window == window.top) { // if not iframe
var link = getLocation(window.top.location.href);
if (link.pathname !== expectedPathname) {
link.pathname = expectedPathname;
window.top.location.replace(link.href);
}
}
You can use HTTP referer header on server-side. If the page is opened in IFRAME - the referer contains parent page address. Otherwise, it is empty or contains different page.

How to handle links in Phonegap + JQM app?

I am building an app with Phonegap and jQuerymobile. The app roughly works like this:
1) The app downloads a ZIP file from a public server and then unzips them to a local folder. I got the local folder path from fileSystem.root.toNativeURL() (in OS, it's something like this: file://var/mobile/Container/Data/Application/xxxx/Documents/)
2) App redirects to HTML that was unzipped in local folder (ex: file://var/mobile/Container/Data/Application/xxxx/Documents/index.html)
I am now facing issues b/c inside the index.html file, all the links are absolute path (ex: Link). This breaks all the links since (I assume) they are all now pointing to file://content/index2.html instead of file://var/mobile/Container/Data/Application/xxxx/Documents/content/index2.html.
My question is, how should I handle the links? I am thinking i should just rewrite all the links to force prepend the local folder URL in front of it. Is there a better way?
And if rewriting links is the way to go, how can I do this with jQuerymobile? I did this in jQuery which seems to work http://jsfiddle.net/jg4ouqc5/ but this code doesn't work in my app (jQueryMobile)
When you are loading index.html, you are getting file://some_path/..../index.html as your base URL. Any links which will be encountered now own-wards can be resolved in relation to the base URL.
You would know your scenario better. There could be multiple ways in which this can be fixed.
Have a contract with the CMS/Code generator. Links should always be generated either Relative to the base URL or Absolute. The links you are getting in the page are wrong - Link it ideally should be Link or fully qualified like https://www.google.com.
If you want to change the URL then you can use native code to change it after unzipping the content. It will be really straight forward.
If you want to change the URL in browser then you will have to persist the base url and then take care of couple of things:
a. absolute urls - In your case you can just check the window.location.protocol, if it starts with 'http' and then skip it.
b. sub-directories
Here is a small I have written:
Note: I have not tried this code and you might have to change it according to your need.
$(document).ready(function(){
var base_file_name = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
//In index.html (persist this value in native)
var baseUrl = window.location.href.replace(base_file_name, "");
$("a").each(function () {
this.href = baseUrl + this.pathname;
$(this).click(function (e) {
e.preventDefault();
alert(this.pathname);
window.location.href = this.href;
});
});
});
The example you linked should work, make sure you have the <base> set correctly and that you are using the correct string to replace.
Yeah, your going to have to normalize all URL's when your page loads. I can't test with phonegap right now, but your basePath will need to be one of the following:
The file path as you described in your answer (not likely)
window.location.origin (optionally including window.location.pathname)
CODE:
// mini dom ready - https://github.com/DesignByOnyx/mini-domready
(function(e,t,n){var r="attachEvent",i="addEventListener",s="DOMContentLoaded";if(!t[i])i=t[r]?(s="onreadystatechange")&&r:"";e[n]=function(r){/in/.test(t.readyState)?!i?setTimeout(function(){e[n](r)},9):t[i](s,r,false):r()}})
(window,document,"domReady");
domReady(function () {
var anchors = document.getElementsByTagName['a'],
basePath = /* get your base path here, without a trailing slash */;
Array.prototype.forEach.call(anchors, function( anchor ){
anchor.setAttribute('href', basePath + anchor.getAttribute('href'));
});
});
Remove the forward slash from the beginning of your links.
href="content/index2.html">

Making insecure images sources secure client-side

I let users on my VanillaForums forum choose whether or not to use the https protocol and I want to test if I can change image sources on the client's side using jQuery.
I want this code to change the protocol in the image source links to // instead of http:// and load before the images have loaded, so I used .ready():
$(document).ready(function () {
if (window.location.protocol == "https:") {
var $imgs = $("img");
$imgs.each(function () {
var img_src = $(this).prop("src");
if (img_src.indexOf("http://") < 0) return;
var new_img_src = img_src.replace("http:", "");
$(this).prop("src", new_img_src);
});
}
});
While it does work in changing the image sources, the URL bar still shows this:
And the console gives a warning that http://someimageurl... is not secure.
Do I need to move the code to the top of the page or will that not make a difference?
It needs to be done server side for the browser not to throw an insecure connection warning. The file with the responsible code is /library/core/functions.render.php, which you can see here.
$PhotoURL is the variable that needs to be changed. Using the following makes sure all images are loaded over the https: protocol: str_replace('http://', 'https://', $PhotoURL).
I usually don't mind global scope on smaller software but in something as big as Vanilla it's like finding a needle in a haystack.
I couldn't find any other fixes for Vanilla in particular so I hope this helps people.

How to go to url in same server without setting complete url address - JavaScript (with/without) jQuery

I know how to go to link / url / address, like;
window.location = "www.example.com/index.html";
or
document.location.href="www.example.com/index.html";
But suppose I want to navigate from index1.html to index2.html, how can i achieve this without providing the www.example.com/ prefix? Please don't suggest that I set www.example.com/ in a global variable / constant. The address may change to www.example2.com/subfolder1/subfolder2/ to www.examplea.com/.... The mentioned methods works only in the case of root pages. I mean, providing document.location.href="index.html"; will navigate the browser to rootdomain/index.html, even if I am staying in rootdomain/section1/section2/somepage.html. But I want to navigate to rootdomain/section1/section2/index.html
How can I achieve this by providing just the page name?
If you have a / at the beginning of your string, it'll go to the local page:
window.location = "/index.html"
Just like you would do otherwise, but using the relative path:
document.location.href = '/index2.html'; //relative path
window.location.pathname = 'index2.html';
You can also just use relative urls on the document.location.href.
What might be even better is window.location.assign('index2.html');. This is especially useful when you're at www.example.com/foo/.../index1.html and don't want to specify the whole path to get to www.example.com/foo/.../index2.html.
For more options, see https://developer.mozilla.org/en-US/docs/DOM/window.location .

Path to included Javascript page

How do I get the absolute or site-relative path for an included javascript file.
I know this can be done in PHP, (__file__, I think). Even for an included page, one can check the path (to the included file). Is there any way to have this self awareness in Javascript?
I know I can can get the page URL, but need to get the JS URL.
Eg. Javascript needs to modify the src of an image on the page. I know where the image is relative to the JavaScript file. I don't know where the Javascript is relative to the page.
<body>
<img id="img0" src="">
<script src="js/imgMaker/myscript.js"></script>
</body>
function fixPath(){
$$("#img0")[0].set('src','js/imgMaker/images/main.jpg');
}
Please do not tell me to restructure my function - the example is simplified to explain the need.
In the actual case, a Mootools class is being distributed and people can put it into whatever folder they want.
I would just read the src of the script element, but the class can be part of any number of javascript files, so I can't know what the element looks like.
JavaScript (not JScript) has no concept of file names. It was developed for Netscape back in the days. Therefore there is no __file__ feature or anything similar.
The closest you can come are these two possibilities:
What you already mentioned: Harvest all src attributes of all JS files and try to figure out which one is the right.
Make it a necessary option, that the path to the images must be set in the embedding HTML file. If not set, use a reasonable and well-documented default:
<script type="text/javascript">
var options = {
'path_to_images': '/static/images/' // defaults to '/js/img/'
};
</script>
Based on http://ejohn.org/blog/file-in-javascript/
(function(){
this.__defineGetter__("__FILE__", function() {
return (new Error).stack.split("\n")[2].split("#")[1].split(":").slice(0,-1).join(":");
});
})();
(function(){
this.__defineGetter__("__DIR__", function() {
return __FILE__.substring(0, __FILE__.lastIndexOf('/'));
});
})();
Then later
img.setAttribute('src', __DIR__ + '/' + file);
if you have folders:
/webroot
/images
/scripts
Then images would be an absolute path of /images/whatever.jpg and scripts would be an absolute path of /scripts/js.js
I'm using the following method to get the base URL and using it for loading the other prorotypes, maybe this is what you need. Lets say current script name is 'clone.js'.
/*
* get the base URL using current script
*/
var baseURL = '';
var myName = 'clone.js';
var myPattern = /(^|[\/\\])clone\.js(\?|$)/;
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var src;
if (src = scripts[i].getAttribute("src")) {
if (src.match(myPattern)) {
baseURL = src.replace(myName, '');
break;
}
}
}
Var baseURL should contain what you need.
The path to the JS is irrelevant; links in the HTML file are always relative to the HTML file, even if you modify them from external JS.
[EDIT] If you need to build a path relative to the current web page, you can find its path in document.location.pathname. This path is relative to the web root but you should be able to find a known subpath and then work from there.
For example, for this page, it pathname would be /posts/1858724. You can look for posts and then build a relative path from there (for example posts/../images/smiley.png)
I know this question was asked awhile back but I have a similar situation to Sam's.
In my case, I have two reasons for the situation:
The user can access different sub-domains, each with its own index page.
The user can enter a password that causes index.php to adjust the paths.
Most of the references point to the same src locations for the scripts, but some do not. For instance, those at a different level of the tree would require a different path.
I addressed it by assigning an id to the index page's script tag. For example, the head might include...
<script id='scriptLocation' type='text/javascript' language='javascript' src='../scripts.test/script.js'></script>
My JavaScript is then able to read the path...
var myPath = document.getElementById("scriptLocation").src;
Found another approach, perhaps someone with more JS ninja can flush this out.
CSS stylesheet are able to find the node that called them using document.stylesheets.ownernode.
I could not find a similar call for javascript files.
But, in some cases, if one can include a CSS file together with the javascript, and give the first rule some unique identifier.
One can loop through all stylesheets till they find the one with the identifier [if(document.stylsheets[i].cssRules[0] == thisIs:myCSS)], than use ownerNode to get the path of that file, and assume the same for the JS.
Convoluted and not very useful, but its another approach - might trigger a better idea by someone.

Categories