decodeURI / replace %20 in URL issues - javascript

The following code is used to get URL parameters.
<script type="text/javascript">
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
<script type="text/javascript">
var url = window.location.protocol + "//" + window.location.hostname;
</script>
The page with the above code is accessed from a link on another page. Within that link i'm passing in a news item ID and Title.
When the page with the above code loads the Title in the URL has %20 in place of all spaces.
I've read up on this and found i need to use decodeURI or decodeURIComponent. I've tried to do this in a number of places and alerted the result in the browser but i can't seem to get rid of the %20 from the title within the URL so its obvious i'm not doing it in the right place.
this is my result....
http://PAGE URL HERE/NewsArchive.aspx?Story=New%20site%20launched&ID=17
I believe i somehow need to include a regular expression of /%20/g,"-" in the replace of the parts variable, however i have next to no knowledge of regex.
Could someone let me know what i need to do as i'm drawing a blank. I've seen a number of similar articles but nothing that explains it to my low level of knowledge.
I also post on SharePoint Stack Exchange as this is being used with SharePoint but i haven't had any answers that have worked for me.
Any help appreciated.

I am not sure I understand the question, but it seems like you just want to retrieve the parameters? If you open the developer console (f12 in chrome) on the page with parameters in the URL you can type window.location and see all the properties of the object. If you type window.location.href you can see the full URI. An easy way to separate this is using .split.
window.location.href.split('?')[1] will give you everything after the ? character. You can do decodeUri(window.location.href.split('?')[1]) to get a normal string.
Just keep in mind the arrays returned by split are zero indexed.
Edit in response to the comment:
The technology you're looking for is history.replaceState. More details here. I would highly recommend a thorough skimming.
history.replaceState(null, "/NewsArchive.aspx", "Story=New-site-launched&ID=17")

Related

Is this JavaScript injection (DOM-based) real or false positive?

I'm trying to grasp JavaScript DOM-based injection attacks better, so I would appreciate some input on this.
I have this output from Burpsuite as "firm" indicating it should be something here.
So the the main page loads a .js file with the code below.
Data is read from document.location and passed to eval() via the following statements:
var _9f=document.location.toString();
var _a0=_9f.split("?",2);
var _a1=_a0[1];
var _a2=_a1.split("&");
var sp=_a2[x].split("=");
djConfig[opt]=eval(sp[1]);
If I understand this correctly, it gets the content after '?' in the url, then splits the parameters after '=' and then evals the second array of that. So www.domain.tld?first=nothing&second=payload, is that correct?
Given that it's already inside of a js file, I'd assume I don't need the < script > tags in the payload? I really can't get it to fire anything so I'm doing it wrong obviously. Would appreciated some input to understand this better, not just a code snippet but some explanation would be great.
...it gets the content after '?' in the url, then splits the parameters after '=' and then evals the second array of that...
Almost. It gets the part of the string after the first ?, splits that into an array of parameters (by splitting on &), then gets the value of the xth parameter (the one at index x), splits it to get its value, and evals that.
This means the page executes code entered into it via the query string, which means Mary can give Joe a URL with code in it that will then execute within the page when Joe opens it, which is a potential security risk for Joe.
Say x is 2. This URL would show an alert: http://example.com/?a=1&b=2&c=alert(42)
var x = 2;
var _9f="http://example.com/?a=1&b=2&c=alert(42)";
var _a0=_9f.split("?",2);
var _a1=_a0[1];
var _a2=_a1.split("&");
var sp=_a2[x].split("=");
/*djConfig[opt]=*/eval(sp[1]);
Here's an example on JSBin: https://output.jsbin.com/cibusixeqe?a=1&b=2&c=alert(42)
How big a risk it is depends on what page this code is in.
Since the code doesn't use decodeURIComponent there are limits on what the code in the query string can be, though they can probably be worked around...

JS split OR Logical Operator

User inputs a web address that I want to get only the tail from, as I do know what site he inputs.
So first I want to remove the "main" URL and get what ever is at the end, so my action is:
Original link: http://example.com/something
var n=e.split("http://example.com/");e=n[1];
And I will get "something"
The problem is that site can also be secured, thus having https not http. Therefore the split wont work.
How do I define a split function, that would work like this:
split("http://example.com/ || https://example.com/")
I do not want to split by looking at "//" or anything of that sort, I want an exact address.
If you like it clear and want to avoid regular expressions, try this:
var n=e.split("http://example.com/",2).pop().split("https://example.com/",2).pop();
If you wish to know the host you can do so by using this code instead in JavaScript:
window.location.host
Source Get The Current Domain Name With Javascript (Not the path, etc.)
You can also use window.location.path to get the URL that was requested, combining those you get:
window.location.host + window.location.pathname
For me, this outputs stackoverflow.com/posts/25203020/edit while writing this reply.
var s = "http://example.com/something";
function split (url) {
var r = /([^:]+):\/\/([^\/]+)\/(.*)/gi;
var a = r.exec(url)
return [a[1], a[2], a[3]];
}

Need help rewriting a url with JavaScript/Jquery

I have a userscript (http://userscripts.org/scripts/show/179402) that I'm writing that adds a bar to Google Sites like the one they removed. I'm needing the script to take the value of the search field and add it to a url (Replacement URL) and have it replace the url (Original URL) on the bar. In other words, I need to update it where the search term carries over to other pages, like the original google bar they removed.
I've tried this a few different ways. One way I tried was getting the value this way. Which, gets the value fine.
$('#gbqfq').keyup(function() {
var searchterm = this.value;
});
Then I've tried to add the search term to a url that replaces the original URL this way
var url1search = "https://www.google.com/search?q="+searchterm;
$('#url1').attr("href", url1search);
How do you replace a url with a new url plus a variable?
I'm very new to JavaScript, I'm making this script to try to learn it. If someone can help me figure out how to do this I would appreciate it very much.
Ah sorry, I see your problem. searchterm is only defined inside the anonymous function, it would be undefined elsewhere. Try moving rest of the script inside that function too.

Passing 2 URL Parameters?

I need to pass 2 URL parameters in a URL. The URL originates in an email and the user will click the link directing them to my site. The first parameter triggers a script on the page the second parameter is for a module my CMS will render from the parameter.
First Parameter is : message=1 (This parameter triggers the javascript)
The second Parameter is: name={tag_recipientfirstname} (My CMS will render the module)
The script that is called for the first looks like this:
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('message=1') != -1) {
$j("a.message").colorbox({
open:true
});
}
$j("a.message").colorbox(); //not related to URL parameter
});
</script>
The second parameter is used on the page as:
<div>
<p>{ module_url,name} (again CMS will render this module)</p>
</div>
EDIT
I realize I left a couple things out:
First: How do I pass both parameters so they will both function as listed above?
And the CMS I am using is Business Catalyst.
//split the `location.search` string at the ampersands
var search_arr = window.location.search.replace('?', '').split('&'),
len = search_arr.length,
get_vars = {},
tmp = [];
//iterate through the key/value pairs and add them to the `get_vars` object
for (var i = 0; i < len; i++) {
tmp = search_arr[i].split('=');
get_vars[tmp[0]] = tmp[1];
}
//you can now access your GET variables through the `get_vars` object like: `get_vars.name`
//you can check for the existence of a certain GET variable like this
if (typeof(get_vars['message-1']) != 'undefined') {
$j("a.message").colorbox({
open:true
});
}
Here is a demo:http://jsfiddle.net/aBH8K/1/ (http://jsfiddle.net/aBH8K/1/show/?message-1=3 to see with get var)
Some related documentation:
window.location: https://developer.mozilla.org/en/DOM/window.location
Your question is not so much about generic development, rather a very specific commercial product; I do not know which plan you subscribed (free o pay-for?) with them but in any case it would be best to go through their support (see also my conclusion)
Nevertheless I'll try to put you on the right track.
Your questions
First,
the url in the email
In the email you will have somehow to build a link with the two parameters you want as #Jasper is explaining.
this means something like:
http://yourwebsite.com/destination/path/?message=1&name={tag_recipientfirstname}
Everything after the question mark is a GET query string.
Parameters are separated by the "&" symbol.
I definitely don't know how properly build urls in BC emails, but I feel like it should be an automated somewhere allowing you to specify additional parameters if you need.
the javascript
What you got will still work. It's not very nice, and you can use Jasper's solution or any other such as How can I get query string values in JavaScript?
Nothing to do then unless you want to make it better and more robust.
Business Catalyst (the page)
You usually have ways in a CMS to retrieve get parameters. Often something like
{ GET.param_name }
One step back
I am no expert with BC, but I have the feeling that you are taking a complicate path for something that is probably already baked in.
Again I suggest you go into their support section (though it's rather confusing I must say!) and try to understand what's the best way to achieve your objective. There are always many ways to skin a poor cat.
If you are getting support in your plan, definitely go that way and try to explain what you objectives are rather then how to achieve the technical solution that you think is the good one!

Replace end characters of current URL with bookmarklet

Is there a way to replace all characters after the last backslash in the currentURL with another string via javascript bookmarklet?
I'm doing a lot of auditing work with Sharepoint sites and having to manually look at the settings pages for sites by entering strings to the end of a URL. For example, I might go to a site like:
https://site.com/..../default.aspx
And I replace the "default.aspx" with "_layouts/user.aspx" and reload the new page so it is now at:
https://site.com/..../_layouts/user.aspx
It's not always "default.aspx", so I can't just use a simple string replace. I know there is a way to manipulate the URL via a javascript bookmarklet, but my knowledge of how to do that is limited at best. Any help or guidance would be greatly appreciated
I don't know if this is what you thought, but if you just want to change the last part of the url with something else, you could use this bookmarklet
javascript:(function(){
var curloc = document.location.href.split('/');
var urlEnding= '/_layouts/user.aspx';
curloc = curloc.splice(0,curloc.length-1).join('/')+urlEnding;
document.location.href = curloc;
})();
You could replace the fixed url with
prompt('Enter your url:', '_layouts/user.aspx');
if you need to change the last part each time.
I hope this helps.

Categories