Okay so here's the problem.
<a>
Tag on the website has a href of
/news-features/8/news-headlines/103818/these-pupils-deserve-better
and of course the domain in the beginning let's say it is:
http://www.webserver.com/
Therefore the whole link is
http://www.webserver.com/news-features/8/news-headlines/103818/these-pupils-deserve-better
However, it should be:
http://www.oldham-chronicle.co.uk/news-features/8/news-headlines/103818/these-pupils-deserve-better
So it is linked to the website information is taken from.
My JQuery function is
var base = "http://www.oldham-chronicle.co.uk/";
$('a').each(function(index, element) {
element.href = element.href.replace("http://dev.liveoldham.com/", base);
});
Which locally works fine as it gives me the correct link however the same code on a webserver gives me:
/news-features/8/news-headlines/103818/these-pupils-deserve-better
Now I am not sure what is the fault, is it the .htaccess and it's rewrite rule or is it something else?
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">
tl;dr: A bookmarklet that opens in a new tab: random link (with specified multiple html-classes) from a specified domain and code that works with current logins. Thank you.
short version of butchered code:
javascript:
(
var % 20 site = domain.com
function() {
window.location.host == site
void(window.open(document.links[Math.floor(document.querySelectorAll("a.class1, a.class2"))].href, '_blank'))
}();
//beautified with: http://jsbeautifier.org/
To whom it may concern:
I have searched around for a while and even considered switching services but although some come close or are similar to my particular request, none have served to address everything the request entails.
Execute the script on a specific domain even when no page from said domain is currently open. If login authentication for attaining the information or data for execution is required, read or work in conjunction with existing session.
Fetch from a specific domain host, a random link out of all links on that domain with a certain html-class (or indeed otherwise) using preferably, css-selectors.
Open the results in a new tab.
From butchering such similarities, the result became something like this:
//bookmarklet
javascript:
//anonymous function+ wrapped code before execution
(
// function global variables for quick substitution
var %20 site = domain.com
function(){
//set domain for script execution
window.location.host == site
//open new tab for
void(window.open(document.links
//random link
[Math.floor
//with specific classes (elements found with css selectors)
(document.querySelectorAll("a.class1, a.class2"))
]//end random-query
.href,'_blank' //end page-open
)//end link-open
)//end "void"
}//end function defintion
//execute
();
//(tried) checked with:
//http://www.javascriptlint.com/online_lint.php
Lastly, i have attained at most, basic css knowledge. I apologise if this request has anybody headdesking, palming or otherwise in gtfo mode. It is only too sad there is apparently no tag for "Warning: I DIY-ed this stuff" in StackExchange. However, i still would like answers that go into a bit of depth of explaining why and what each correction and modification is.
Thank you presently, for your time and effort.
Theoretically, the following code should do what you want:
window.addEventListener('load', function ( ) {
var query = 'a.class1[href], a.class2[href]';
var candidates = document.querySelectorAll(query);
var choice = Math.floor(Math.random() * candidates.length);
window.open(candidates.item(choice).href, 'randomtab');
}, true);
window.location.href = 'http://domain.com';
But it doesn't, because the possibility to retain event listeners across a page unload could be abused and browsers protect you against such abuse.
Instead, you can manually load the domain of your choice and then click a simpler bookmarklet with the following code:
var query = 'a.class1[href], a.class2[href]';
var candidates = document.querySelectorAll(query);
var choice = Math.floor(Math.random() * candidates.length);
window.open(candidates.item(choice).href, 'randomtab');
You could wrap the above in javascript:(function ( ) { ... })(); and minify as before, but it already works if you just minify it and only slap a javascript: in front.
I understand your situation of being an absolute beginner and posting "DIY" code, but I'm still not going to explain step-by-step why this code works and yours doesn't. The first version of the code above is complex to explain to a beginner, and the list of issues with the code in the question is too long to discuss all of them. You'll be better off by studying more Javascript; a good resource with tutorials is MDN.
I created a bilingual website using two databases:
www.martyregan.com/
www.martyregan.com/jp/
You can choose the language of the website using the 'Website Language' flags, but currently the links only bring you to the homepage. The paths/URLs on both sites are exactly the same, other than /jp/ directory on the Japanese site.
I'm looking for a way to alter the hyperlinks to go to the parallel page, based on the URL of the page the visitor is currently on. I figure it'd be quite simple being that the paths are identical, but not really sure where to start with my little knowledge of jquery.
This assumes your language is accessible as seen below.
"http://" is removed from the URL for convenience.
$(function(){
var lang = 'jp';
$('a').attr('href', function(x, url){
var split = url.replace(/(http:)?(\/\/)?/, '').split('/');
return split.shift() + '/' + lang + '/' + split.join('/');
});
});
You may be able to get away with using the <base> tag depending up on the browsers you need to support. You can just set that to whatever the base is by acquiring it from the server.
If you want to use jQuery to do it, it should be fairly simple if all of your hrefs are absolute:
$("a").attr('href', function (_, href) {
return $("base").attr('href') + href;
});
This assumes that you are using <base>. If you're not you can get the path from window.location.path, or even some other element on the page.
In case you are confused, the JavaScript is only required if <base> is not enough to work on its own
Can anybody explain how the following javascript variables:
document.referrer
document.location.href
or the http REFERRER header, could come to be 'javascript:window["contents"]' ?
Not only do I not understand how they could be set to a javascript uri - but window.contents isn't a standard DOM attribute in any browser that I know of... (It is window["contents"], not window["content"])
I believe I found the solution to this..
There are some javascripts in the wild which seem to create iframes using code (something) like this:
var contents = '<html>......</html>';
var ifr = document.createElement('iframe');
ifr.contentWindow.open();
ifr.contentWindow.write(contents);
some particular combination of this sometimes ends up specifying either the href of the iframe , or the referrer, as "javascript:window['contents']" - i.e. the javascript variable which temporarily holds the page data.
(still not completely finalized on the details, but that's the basic idea)
Question:
IE and Firefox / Safari seem to deal differently with BASE HREF and Javascript window.location type requests. First, is this an accurate description of the problem? What's going on? And what's the best cross-browser solution to deal with this situation?
Context:
I have a small PHP flat file sitelet (it's actually a usability testing prototype).
I dynamically generate the BASE tag's HREF value in PHP, i.e. if it's running on our company's server, it's:
$basehref = 'http://www.example.com/alpha/bravo/UsabilityTest/';
and on my local dev machine, it's:
$basehref = 'http://ellen.local/delta/echo/foxtrot/UsabilityTest/';
For one of the tasks, I collect some user input, do some transformations on it in Javascript, and send to the server using code like this:
function allDone() {
// elided code for simplicity of stackoverflow question
var URI = "ProcessUserInput.php?";
URI = URI + "alphakeys=" + encodeURI( keys.join(",") );
URI = URI + "&sortedvalues=" + encodeURI( values.join(",") );
window.location = URI;
}
Both the javascript file (containing function allDone()) and the processing PHP script (ProcessUserInput.php) live in a subdirectory of UsabilityTest. In other words, their actual URL is
http://www.example.com/alpha/bravo/UsabilityTest/foxtrot/ProcessUserInput.php
aka
$basehref . '/foxtrot/ProcessUserInput.php'
The Problem
IE's JavaScript basically seems to ignore the BASE HREF. The javascript and the PHP processor live in the same directory, so the call to ProcessUserInput.php works out fine. The input gets processed and everything works fine.
But when I test on Firefox, the JavaScript does appear to use the BASE HREF, because the script's output gets sent to
$basehref . '/ProcessUserInput.php'
This breaks, because ProcessUserInput.php is in a subdirectory of basehref. However, if I add the subdirectory name to the javascript, it no longer works in IE.
Solutions?
I can think of a few ways to solve this:
In Javascript, read the HREF property of the BASE tag and manually prepend to var URI in the javascript, calling a fully-resolved absolute URL
Process the .js file with PHP and insert the $basehref variable into the script
Move the files around
Something else?
I'm sure there must be other ways to solve this too. What's the best way to deal with BASE HREF in JavaScript when IE and Firefox apply it differently in JavaScript?
Using the assign method of window.location seems like the most straightforward answer.
Instead of
window.location = URI;
I'm using this:
window.location.assign( URI );
which is doing the right thing in both IE and Firefox.
IE and Firefox / Safari seem to deal differently with BASE HREF and Javascript window.location type requests.
Yes, this is a long-standing difference going back to the early days of Netscape-vs-IE.
IE enforces base-href only at the point a document element is interacted-with. So, you can createElement('a'), set a relative href and click() it*, but the base-href will be ignored; appendChild it to the document containing the base-href, and it'll work.
On the other browsers the base-href is taken as global per-window and always applied. Which is right? It seems to be unspecified. The original JavaScript docs say only that location.hash (and hence, location applied as a string):
represents a complete URL
So setting it to a relative URL would seem to be an undefined operation.
(*: link.click() is a non-standard method supported by IE and Opera)
read the HREF property of the BASE tag and manually prepend
Probably what I'd do, yeah, if you're dead set on using <base>.
I believe you want to modify window.location.pathname, not window.location. window.location is a Location object, that has multiple variables. As a result, the effects of changing it is not well defined. However, window.location.pathname is defined as the path relative to the host, which is what you want.
If you want to read up more on the many variables you can change in window.location, I'd check here. According to Mozilla's documentation, changing any variable in window.location should reload the page with a new URL corresponding to those changes.
I had the same problem today, after some researching, couldn´t findn any way to override this issue in IE9, what is a requiremente for my project, so, i did the following approach (jquery based, but it´s really easy to make it in simple javascript).
href = function(url){
if ($("base").length > 0 ){
location.href= $("base").attr("href")+url;
}else{
location.href = url;
}
}
And then, change
location.href= 'emp/start'
to
href('emp/start');
just add $('base').attr('href') before the link. (using jquery) or
document.getElementBytagname('base').href
You can always use Vanilla JS :)
var href = document.getElementBytagname('base')[0].href
I hope this helps.