Cut string obtained with Javascript inside hyperlink - javascript

I made a bookmark that users can add and it sends them to my site capturing the referrer.
Bookmark
My problem is that for some reason the location.href part instead of printing http:// it prints: "http%3A//". I want to remove it and get just the domain.com
I have a similar code that maybe could be useful but I'm having a hard time figuring out how to implement it inside HTML.
// Function to clean url
function cleanURL(url)
{
if(url.match(/http:\/\//))
{
url = url.substring(7);
}
if(url.match(/^www\./))
{
url = url.substring(4);
}
url = "www.chusmix.com/tests/?ref=www." + url;
return url;
}
</script>
Thanks

In most browsers, the referrer is sent as a standard field of the HTTP protocol. This technically isn't the answer to your question, but it would be a cleaner and less conspicuous solution to grab that information server-side.
In PHP, for example, you could write:
$ref = $_SERVER['HTTP_REFERER'];
...and then store that in a text file or a database or what-have-you. I can't really tell what your end purpose is, because clicking a bookmark lacks the continuity of browsing that necessitates referrer information (like the way that moving from a search engine or a competitor's website would). They could be coming from a history of zero, from another page on your site or something unrelated altogether.

Like already stated in my comment:
Be aware that this kind of bookmarking may harm users privacy, so please inform them accordingly.
That being said:
First, please use encodeURIComponent() instead of escape(), since escape() is deprecated since ECMAScript-262 v3.
Second, to get rid of the "http%3A//" do not use location.href, but assemble the location properties host, pathname, search and hash instead:
encodeURIComponent(location.host + location.pathname + location.search + location.hash);

Related

Node js setup an Anchor [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

Dotnet Return Url Missing Parameter

Here's a head-scratcher:
I have a Dotnet Application which signs a user out after a certain inactive time period. A JavaScript function using an action defined in the relevant CSHTML sends the user to a certain controller method which will sign them out.
When the JavaScript code decides that the user should be signed out, it uses the following line to do so:
location.href = settings.actions.expireSession + '?returnUrlString=' + currentUrl;
where settings.actions.expireSession is defined as:
expireSession: '#Url.Action("Expire", "Session")'
and the return url string getting into the location.href looks like this:
http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84&caseId=173
which is correct, and the entire string assembled together with the url action looks like this:
"/Session/Expire?returnUrlString=http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84&caseId=173"
I set up a breakpoint at the point of entry in the relevant method, but what arrives in the string parameter named "returnUrlString" there is missing the "caseId":
http://localhost:49574/?returnUrl=http%3A%2F%2Flocalhost%3A49574%2FReport%2FReportWithUserIdAndCaseId%3FuserId%3D84
consequently, when I enter my username and password to log back in, I get redirected to the following url:
http://localhost:49574/Report/EntrySummaryReportWithPatientIdAndVisitId?userId=84
which fails because it's missing a crucial parameter.
Have I missed anything obvious? Is there something else in the automated background of Dotnet's addressing/redirection system that could be contributing to this mysterious disappearance?
A huge thanks to everyone for reading this, and a gargantuan thanks for contributors!
- Ilia
You need to escape the Url before it is sent to the Session/Expire page.
See this previous question for information on encoding it in Javascript:
Encode URL in JavaScript?
Once you have returnUrlString on your Session Expire page, you should then unescape it and direct the user to it.
The problem is that the Url to the Session/Expire page would be:
"/Session/Expire?returnUrlString=http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84&caseId=173"
What the server sees is:
Page: "/Session/Expire?, QueryString ReturnUrlString: returnUrlString=http://localhost:49574/Report/ReportWithUserIdAndCaseId?userId=84, QueryString CaseId: &caseId=173"
It is interpreting your &caseId as part of the /Session/Expire URL. This is why it disappears.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

Javascript - Check for Hash, Ignore Analytics Code following

We are adding a video to the home page of a site, and want to be able to automatically pop up the video (in a lightbox-style container) whenever the #video tag is present in the URL:
http://www.domain.com#video
The video needs to pop up if a link is clicked internally on the site (ie: <a href="#video">) and also if the hash is present in the URL on page load.
Easy enough to check for the hash in the URL using window.location.hash or when a link with the hash is clicked and fire the associated javascript function. That's working as expected without any issues.
However as this URL will be sent out in emails with Google Analytics code automatically added, the analytics code is appended to the end of the URL:
http://www.domain.com#video?utm_source=...
Because the analytics code will change with each email campaign, I can't do a simple Javascript replace() to ignore the analytics code.
How do I go about checking whether the hash is present in the URL, but ignore anything after a ? if present?
Isn't the proper form of a URL to have the hash at the end after the query parameters? Then, the location.hash variable will work properly and you won't need special code. Your URL should look like this and then you can just directly use location.hash which will be #video:
http://www.domain.com?utm_source=xxx#video
I don't advise this as the solution (I think you ought to get the URLs fixed to be legal), but you can use this code to parse the hash value out of the URL even if it's in the illegal position:
var matches = window.location.href.match(/#(.*?)(\?|$)/);
if (matches) {
var hash = matches[1];
}
This code extracts from the "#" to either end of string or "?" whichever comes first. You can see it run on a bunch of test URLs here: http://jsfiddle.net/jfriend00/HuqL7/.
location.hash.match(/[^?]*/)
Assuming the hash is always first, that should do it.
(This is a literal answer to your question, but there is a huge caveate) Technically, you can just test:
var h = window.location.hash;
var ind = h.indexOf( '?' );
var test = ind <0?h:h.substr(0, ind)
If you want Google Analytics to work, you may have problems #. The rule is that everything after a # is not sent to the server, which means that your Analytics may go out the window. You need to make sure that your hash is added after all of the Google stuff. If it is, then you won't need to worry about testing anything.

Loopback jQuery AJAX Request

What is the best way to build a loopback URL for an AJAX call? Say I have a page at
http://www.mydomain.com/some/subdir/file.php
that I want to load with an AJAX call. In Firefox, using jQuery this works fine:
$.post('/some/subdir/file.php', ...);
Safari/WebKit tries to interpret this as a location on the local filesystem (so it ends up translating to 'file://some/subdir/file.php'). Not only does this not point to anything useful, it also results in a security error.
Is there a way to accomplish this without hard-coding the domain into the URL? I'd like to make this as domain-independent as possible.
Update
I ended up parsing out the base url from location.href and throwing it into an accessible jQuery function like this:
/**
* Retrieves the current root URL.
*
* #return string the root URL
*/
$.fn.rootUrl = function() {
var url = location.href;
return url.substring(0, url.indexOf('/', 7));
};
Wow, that's pretty poor of Safari/WebKit, IMO.
You could observe document.href, count the slashes, and add that many "../" to the beginning of your URL.
You could have the server insert its own URL as a javascript variable when it serves up the page, then use that variable as part of your Ajax calls. It would then be both secure and automatic.
Alternatively, you can assemble your URL as follows:
'http://'+document.domain

Categories

Resources