Why can't I use relative URLs with IE7? - javascript

I've been Googling for a while and can't seem to find an answer to this question. My problem is as follows:
For my jquery, I need my links to be relative rather than absolute. My PHP is set to return relative urls and everything is working fine, until I test it in IE7. For some reason, IE7 keeps changing my relative urls to abosulute, which breaks my js script. Is this normal? Is there a way to get around it?
For example:
IE8, Chrome, Firefox, Safari etc -
<a href='/page' onclick='click_handler(this);return false;'>clicky</a>
IE7 -
<a href='http://www.myurl.com/page' onclick='click_handler(this);return false;'>clicky</a>

What I do is grab the baseUrl at init, like:
var baseUrl = window.location.href.substring(0, window.location.href.lastIndexOf("/") + 1);
... and then in my URL handler, strip the baseUrl:
var url = $(this).attr("href").replace(baseUrl, "");
Also you can check if the href is "normalized" using .support():
$.support.hrefNormalized
(returns true if the browser makes no modifications when grabbing an href value, so it's currently false in IE.)

If I were you, I'd use browser detection and add a clause to strip the URL down to the relative path. I'm not 100% familiar with jQuery, but I imagine you could do it with a simple split and reconstruction, or REGEX query.
See jQuery URL Parser Plugin: http://plugins.jquery.com/project/url_parser

Looks like it has something to do with security issues - http://blogs.msdn.com/ie/archive/2005/08/15/452006.aspx

Right, it seems the best way to do this is to strip the domain out in jQuery. For anyone that has a similar problem, here is what my click event handler looks like:
var href_attr = element.getAttribute('href');
if (href_attr.indexOf('http://')>-1) {
href_attr = href_attr.substr(location.href.length-1);
};

Here's a modified version of JKS's answer that uses split instead of substring. A little more elegant IMO:
stripBaseUrl : function(url){
var urlArray = url.split("/");
return urlArray[urlArray.length - 1];
}

Related

How to get anything following the domain in a url, using Javascript

What is the best way to get the "anything" part after the domain part, using Javascript:
http://www.domain.com/anything
http://www.domain.com/#anything
http://www.domain.com/any/thing
For http://www.domain.com/#anything I would have to use window.location.hash. But for http://www.domain.com/anything I would have to use window.location.pathname.
I'm using:
window.location.href.replace(window.location.origin, "").slice(1)
Are there any caveats with this solution? Is there a better way?
Caveats:
location.origin is not supported by IE.
Other improvements: .slice is actually calling Array.prototype.slice. A method call that requires a prototype lookup is bound to be slower than accessing the element you need directly, escpeciallly in your case, where the slice method is returning an array with just 1 element anyway. So:
You could use location.pathname, but be weary: the standard reads:
pathname
This attribute represents the path component of the Location's URI which consists of everything after the host and port up to and excluding the first question mark (?) or hash mark (#).
but I think the easiest, most X-browser way of getting what you want is actually simply doing this:
var queryString = location.href.split(location.host)[1];
//optionally removing the leading `/`
var queryString = location.href.split(location.host)[1].replace(/^\//,'');
It's very similar to what you have now, except for the fact that I'm not using location.origin, which, as shown on MDN is not supported by MS's IE...
Another benefit is that I'm not calling Array.prototype.slice, which returns an array, and requires a prototype-lookup, which is marginally slower, too...
window.location.pathname + window.location.search + window.location.hash
I think this one is a little bit better. You dont have to use any functions here...

Parse URL value and remove anything after the last '/'

My website URL is (example) http://mypage.com/en/?site=main. Then comes JavaScript code that, together with PHP, parses the data.
After that, I need some code that will change the URL inside the adress bar to http://mypage.com/en/, that is, removes the stuff after the last / (slash).
If possible, it is should be jQuery/JavaScript code.
I found something that will work.
You have to use a method called replaceState().
Mozilla developer reference
var str = window.location.href;
window.history.replaceState({}, '', str.substr(0,str.lastIndexOf("/"))+"/");
Use split() function in javascript.
Example :
var url = "http://mypage.com/en/?site=main";
alert(url.split('?')[0]);

How to read href attribute with JQuery

I use $(this).attr('href') in JQuery to read the string in href="" attribute.
I have those kind of links:
Firefox and Chrome return me the code correctly. IE return me: http://127.0.0.1/1
How can i do?
You don't need to use the attr function when you're accessing a native property. You could use the anchor element's properties directly to get the pathname (i.e. the HREF without the domain or query string)
Basically: this.pathname
There's a bit of an inconsistency between browsers (some will show a leading forward slash in pathname and others won't). To get around this, just get rid of any potential leading slashes:
this.pathname.replace(/^\//,'')
A working example: http://jsfiddle.net/jonathon/3ET6p/
Even if you choose the other answers, I recommend you use the native .href on the object.
Just as an extra note to this. I fired up a VM of IE6 and all is well :)
Try via DOM element:
$(this)[0].href; or $(this)[0].getAttribute("href");
If the result is still the same, I suggest you using something not starting with the number.
.
I'd suggest checking which browser is being used. If it's IE, check if the current domain is "127.0.0.1". If it's not, do what #Saul suggested.

IE Object doesn't support this property or method

This is probably the beginning of many questions to come.
I have finished building my site and I was using Firefox to view and test the site. I am now IE fixing and am stuck at the first JavaScript error which only IE seems to be throwing a hissy about.
I run the IE 8 JavaScript debugger and get this:
Object doesn't support this property or method app.js, line 1 character 1
Source of app.js (first 5 lines):
var menu = {};
menu.current = "";
menu.first = true;
menu.titleBase = "";
menu.init = function(){...
I have tested the site in a Webkit browser and it works fine in that.
What can I do to fix this? The site is pretty jQuery intensive so i have given up any hope for getting it to work in IE6 but I would appreciate it working in all the others.
UPDATE: I have upload the latest version of my site to http://www.frankychanyau.com
In IE8, your code is causing jQuery to fail on this line
$("title").text(title);
in the menu.updateTitle() function. Doing a bit of research (i.e. searching with Google), it seems that you might have to use document.title with IE.
Your issue is (probably) here:
menu.updateTitle = function(hash){
var title = menu.titleBase + ": " + $(hash).data("title");
$("title").text(title); // IE fails on setting title property
};
I can't be bothered to track down why jQuery's text() method fails here, but it does. In any case, it's much simpler to not use it. There is a title property of the document object that is the content of the document's title element. It isn't marked readonly, so to set its value you can simply assign a new one:
document.title = title;
and IE is happy with that.
It is a good idea to directly access DOM properties wherever possible and not use jQuery's equivalent methods. Property access is less troublesome and (very much) faster, usually with less code.
Well, your line 1 certainly looks straight forward enough. Assuming the error line and number is not erroneous, it makes me think there is a hidden character in the first spot of your js file that is throwing IE for a fit. Try opening the file in another text editor that may support display of normally hidden characters. Sometimes copying/pasting the source into a super-basic text-editor, like Notepad, can sometimes strip out non-displayable characters and then save it back into place directly from Notepad.

Regular Expression for relative links ONLY

I'm creating a javascript that checks for links in the DOM and changes those who are NOT absolute links. Unfortunately I'm not having any luck...
I would like to match only the first type of links below, and add a folder path
link
<a href"http://somesite.net/somepage.html">link</a>
I've used string.replace(/a.+href="([^http]+)"/, 'path'+$1); to no avail...
Can someone help me here? Thanks in advance.
If the regular expression that you've written to solve a problem using just regular expressions starts to look like overkill, then it is probably overkill. Sometimes a simple if statement used in conjunction with regular expressions can do wonders:
$("a").each(function () {
if (!/^http:\/\//.test(this.href)) {
this.href = "http://example.com/folder/" + this.href; // etc.
}
});
You may want to look at the <base> html tag, instead. It allows you to set the path to which all links and images are relative.
http://www.w3schools.com/tags/tag_base.asp
http://www.w3.org/TR/html5/semantics.html#the-base-element
You've created a character class with the square brackets. Remove them. You want a "negative lookbehind", see comment below for info on syntax. Not all languages support this regex feature though.
Javascript doesn't support lookbehind. This may help though: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
You can use
string.replace(/(a.+href=)"(?!http)(.+)"/gi, '$1"path/$2"')
for example sake, I just made a variable with a couple links in it. You can easily adapt the .replace() to work with however you get the links.
var content = 'linklinklink';
// whatever you want to prefix link with
var base='http://somsite.net';
content = content.replace(/(href=")(?!https?:\/\/)([^"]*)/gi,'$1'+base+'/$2').replace(/\/+/g,'/');
Thanks everyone.
I was able to replace relative paths ONLY by using the following syntax:
var basepath = "pathto/";
var html = html.replace(/(<(a|img)[^>]+(href|src)=")(?!http)([^"]+)/g, '$1'+basepath+'$4');

Categories

Resources