I'm using jquery to rewrite a list of links on the page. If the location.host is NOT the vendor location.host AND the cookie isn't set to a specific value then it locates the links and rewrites them to the alternate values. The code I'm using works great in FF but not in IE7. Please help!
<script type="text/javascript">
// link hider
var hostadd = location.host;
var vendor = '172.29.132.34';
var localaccess = 'internal.na.internal.com';
var unlock = 'http://internal.na.internal.com/Learning/Customer_Care/navigation/newhire.html';
// link rewriter
$(document).ready (
function style_switcher(){
//if not a vendor or not accessing from lms reroute user to lms
if (hostadd != vendor && $.cookie("unlockCookie") != unlock){
var linkData = {
"https://www.somesite.com": "https://internalsite.com/something",'../Compliance/something/index.html':'../somethingelse.html'
};
$("a").each(function() {
var link = this.getAttribute("href"); // use getAttribute to get what was actualy in the page, perhaps not fully qualified
if (linkData[link]) {
this.href = linkData[link];
}
});
}
});
</script>
What you could do, if you insert the links dynamic, is store them in a data attribute like data-orglink="yourlink" which wouldnt be transformed by the browser, then check on that -and if its in the object array - change the href. Do you have access to creating the data attribute?
IE7 have problems with internal links, because it puts the host info on, before JS can reach the link..
http://jsfiddle.net/Cvj8C/9/
Will work in all, but IE7. So you need to use full paths if to use JS for this function :(
You had some errors in your JS.
But it seems to work fine?
See: http://jsfiddle.net/s4XmP/
or am i missing something? :)
Related
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">
I'm trying to obtain a hotlink from a url a user gets to via a link in an email
Everything after the ? below:
http://localhost:6547/m/intro/inbox/100003120?hotlink=8095cb20284c935d9ff32c0ed61b28f1&codekitCB=400521239.247318
I need to save that hotlink into a variable to POST to a new url, however my code isn't retrieving the hash or hotlink:
jQuery:
$(document).ready(function () {
// MOBILE HACKS
var path = window.location.pathname;
var hash = window.location.hash;
console.log('dashboard.init: path = '+path);
console.log('dashboard.init: hash = '+hash);
Console:
How would you get the hash/hotlink after the ? in the url above?
You can use window.location.search
That will return everything from the ? on, and then you can parse that as needed.
Theres probably a better answer out there, but I've always just used
window.location.href.split('?')
index [1] will be everything after the ?
I have a functional wordpress theme that loads content via ajax. One issue that I'm having though is that when pages are loaded directly the ajax script no longer works. For example the link structure works as follows, while on www.example.com and the about page link is clicked then the link becomes www.example.com/#/about. But when I directly load the standalone page www.example.com/about, the other links clicked from this page turn into www.example.com/about/#/otherlinks. I modified the code a little bit from this tutuorial http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html. Here is my code. Thanks for the help.
jQuery(document).ready(function($) {
var $mainContent = $("#container"),
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
location.hash = this.pathname;
return false;
});
$(window).bind('hashchange', function(){
url = window.location.hash.substring(1);
if (!url) {
return;
}
url = url + " #ajaxContent";
$mainContent.fadeOut(function() {
$mainContent.load(url,function(){
$mainContent.fadeIn();
});
});
});
$(window).trigger('hashchange');
});
The problem you are expressing is not easily solved. There are multiple factors at stake but it boils down to this :
Any changes to a URL will trigger a page reload
Only exception is if only the hash part of the URL changes
As you can tell there is no hash part in the URL www.example.com/about/. Consequently, this part cannot be changed by your script, or else it will trigger page reload.
Knowing about that fact, your script will only change the URL by adding a new hash part or modifying the existing one, while leaving alone the "pathname" part of the URL. And so you get URLs like www.example.com/about/#/otherlinks.
Now, from my point of view there are two ways to solve your problem.
First, there is an API that can modify the whole URL pathame without reload, but it's not available everywhere. Using this solution and falling back to classical page reload for older browser is the cleaner method.
Else, you can force the page reload just once to reset the URL to www.example.com/ and start off from a good basis. Here is the code to do so :
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
location = location.assign('#' + this.pathname);
return false;
});
It should be noted that this script won't work if your site is not at the root of the pathname. So for it to work for www.example.com/mysite/, you will need changes in the regex.
Please let me know how it went.
I am creating a webapp and I have been using tag in my JSPs to ensure that all my links (both to pages and to resources such as images/css) are always consistent from the root of the application, and not relative to my current location.
Some of the content I am creating using jQuery, for example, I am creating a HTML table by parsing a JSON object and using jquery.append() to insert it in to a div.
My question is, if I want to dynamically create a link using jquery how can I achieve a consistent URL regardless of the page being executed? I have tried just building the html with the tag in it, but no joy.
Thanks!
var baseURL = "/* Server-side JSP code that sets the base URL */";
$("<a />", { href: baseURL+"/my/resource/here.jsp" }); //Your proper link
Or you could do:
var baseURL = "http://"+location.host+"/my/base/url/";
//Which gives you something like http://mySite.com/my/base/url/
Get the root value of your webapp into a string using a jsp tag inside your javascript.
var root = < %=myRootVariable%> //This evaluates to http://www.myapp.com
var dynamicBit = "/foo/bar"
var dynamicLinkUrl = root + dynamicBit
var $newa = $("Hello, world");
$someJQElement.append($newa)
Hopefully none of this will occur in the global namespace. Just sayin'
As far as I know, if you want to load JavaScript or CSS files together with a specific page that is automatically loaded via ajax then you have to put the CSS/JavaScript references within the <div data-role="page"> container.
Example:
<div data-role="page" data-theme="e">
<script type="text/javascript" src="/js/jquery/plugins/plugins.js"></script>
In general, this works fine. However, somewhere along the way, the script url gets modified:
/js/some_sepcial_script.js becomes e.g. js/some_sepcial_script.js?_=1299308309681
Where 1299308309681 is the current Unix timestamp which changes on every request and thus prevents caching. I am pretty sure that this is intended behaviour but does anyone know how you can prevent the timestamp from being appended to the script/CSS urls if you want to make the file cacheable?
Have you tried:?
$.ajax ({
// Disable caching of AJAX response */
cache: false
});
It should globally change ajax requests. I'm just not sure about external scripts.
[EDIT]
This is the source code involved for jquery mobile 1.0a3:
var all = $("<div></div>");
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
to = all.find('[data-role="page"], [data-role="dialog"]').first();
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ){
var newPath = path.get( fileUrl );
to.find('[src],link[href]').each(function(){
var thisAttr = $(this).is('[href]') ? 'href' : 'src',
thisUrl = $(this).attr(thisAttr);
//if full path exists and is same, chop it - helps IE out
thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test(thisUrl) ){
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
Nothing on there adds a cache preventing param.
[EDIT 2]
I know this goes beyond troubleshooting to a work around but have you tried dynamically loading the js like explained here: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
(I know it can be done through jQuery but for testing purposes I'm trying to avoid jQuery)
if I include jQuery 1.4.3 instead of 1.5 everything works fine. That's a sufficient solution for me. Thanks again for your support.
Try running:
$.ajaxPrefilter("script", function (s) {
if (s.cache === undefined) {
s.cache = true;
}
});
Does it change this behavior?