Click ID and open URL? - javascript

I am trying to click on a #ID and open a URL - but [as a newbie] - I can't seem to get it. I am using
$('#Test').click(function() {
OpenUrl('some url');
return false;
});

Something like:
$("#Test").click(function(event){
window.location.href = "some url";
event.preventDefault();
});

Just use window.location = 'some url'
$('#Test').click(function() {
window.location = 'http://www.google.com'
return false;
});
To elaborate a bit, window.location is an object with different quite interesting properties, you can read more about it here. In short, it contains the following properties (quoted from the link):
Property Description Example
hash the part of the URL that follows the #test
# symbol, including the # symbol.
host the host name and port number. [www.google.com]:80
hostname the host name (without the port number www.google.com
or square brackets).
href the entire URL. http://[www.google.com]:80
/search?q=devmo#test
pathname the path (relative to the host). /search
port the port number of the URL. 80
protocol the protocol of the URL. http:
search the part of the URL that follows the ?q=devmo
? symbol, including the ? symbol.
Since window.location is an object, it can also contain methods, which window.location does. By using these methods, instead of just assigning a string to the object, you can exert greater control of how the page is loaded, i.e. force a reload from the server or allow the browser to use a cached entry, skip creating a new history point etc.
Here is an overview of available methods:
Method Description
assign(url) Load the document at the provided URL.
reload(forceget) Reload the document from the current URL. forceget is a
boolean, which, when it is true, causes the page to always
be reloaded from the server. If it is false or not specified,
the browser may reload the page from its cache.
replace(url) Replace the current document with the one at the provided
URL. The difference from the assign() method is that after
using replace() the current page will not be saved in
session history, meaning the user won't be able to use
the Back button to navigate to it.
toString() Returns the string representation of the Location object's
URL.
You can also open resources in new windows if you want to. Please be aware that some users dislike having links opened in new windows for them, and prefer to having to consciously make this decision themselves. What you can do, however, is to mimic some of this functionality in your click-handler and try to figure out which mouse-button was clicked. If it was the middle-mouse button, then most browsers would open the link in a new window. This won't be exactly the same, since users won't be able to right-click and select 'Open in new window', but it might be good enough. Anyway, here's how to open a resource in a new window:
var WindowObjectReference;
function openRequestedPopup()
{
WindowObjectReference = window.open(
"http://www.domainname.ext/path/ImageFile.png",
"DescriptiveWindowName",
"resizable=yes,scrollbars=yes,status=yes");
}
You can read a lot more information here

hm if your OpenUrl function looks anything like this this should work just fine :D
function OpenUrl(url){
window.location = url;
}
btw: why returning false on click??

Related

Redirect to different URL when current URL contains some string

I have a requirement wherein I need to redirect my page to a different URL when my current URL contains some string.
For instance,
If my current URL contains www.testdomain.com or www.testdomain.com/web/region then it should redirect to www.testdomain.com/group/region. I tried the below code but it returns "The requested resource could not be found -- https://www.testdomain.com/web/region/testdomain.com/group/region".
$(document).ready(function() {
if (window.location.href.indexOf("web/region") > -1) {
window.location.href=window.location.hostname+'/group/region';
}
})
It is adding the URL twice here. But when I pass the direct URL window. location.href="www.testdomain.com/group/region" it is working.
Can someone guide me on how do I force redirect my page if the URL contains www.testdomain.com or www.testdomain.com/web/region?
Thanks
Start with // so that the browser knows it's not a relative URI:
window.location.href = '//' + window.location.hostname+'/group/region';
You can also prepend the protocol:
window.location.href = window.location.protocol + '//' + window.location.hostname+'/group/region';
It's adding the URL twice because browsers interpret /group/region as a relative path, automatically prepending the current domain UNLESS otherwise specified. (Maybe others can explain why window.location.hostname doesn't immediately return, thus preventing the browser from assuming a relative path?)
Example: If you explicitly set a domain, the browser will redirect to it as expected.
window.location.href='http://www.google.com/'
Otherwise, if you take away "www."
window.location.href='google.com/'
Your browser will redirect to "www.testdomain.com/google.com", appending the string.
The fix is simple.
Just delete window.location.hostname+ and it will only return the URL once.
Or... for a better user experience, I would suggest using window.location.replace() which DOES NOT save the current page in session history.(You don't want to go back, just to be redirected again!)
SOLUTION:
Replace your return block with this.
window.location.replace('/group/region')

Extract parameter from url path in javascript

I want to extract a part of an url path but i don't know how to do that.
I want to get a value (3252) from a path like this:
/forums/0-3252-1-1-my-topic-title.htm
How can i do that ?
Thank you
If you want to work with URL there is a powerful tool on which you can reply and that is JavaScript Window Location.
The window.location object can be used to get the current page address (URL).
The window.location object have many properties or method.
Some examples:
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current page
window.location.protocol returns the web protocol used (http: or https:)
window.location.assign() loads a new document
Example:
Display the href (URL) of the current page:
<script>
alert(window.location.href);
</script>
Follow link to read more: Window Location

JavaScript browser navbar event

I want to prevent users to navigate to URL´s that are not accessed through html element. Example:
Actually navigating on: myweb.com/news
And I want to navigate to myweb.com/news?article_id=10 by writing this in the browser navigation bar to avoid pressing any element (like <a>).
When the user writes myweb.com/news?article_id=10 in the browser url, at the moment he presses enter, the browser should not allow him to navigate to the url.
I have tried:
//This wont work since jquery does not support it
$(window.location.href).on('change', function() {
//Here check if href contains '?'
alert("Not allowed");
});
//Neither works, doesnt do anything
$(window).on('change', function() {
alert("Not allowed");
});
References:
there is something similar asked here On - window.location.hash - Change?, but im interested in the 'parameter' version of that question.
There are some known solutions :
) Each time a user click a link - you save the page value to a cookie.
Later , at the server- you check that interval ( value-1 ... value+1).
) You can also save to a hidden field and check that value in the server.
So let's say a user is on page 3. ( the server serve that page - so a cookie/hidden value with value 3 is exists)
now he tries to go to page 10 :
you - in the server side - reads the cookie + requested Page number. if the interval is bigger than 1 - then you deny that request.
Try adding an event listener:
window.addEventListener('popstate', function(event)
{
var location = document.location;
var state = JSON.stringify(event.state);
});
To check the URL, The best thing would be to match it against a regex like:
if (url.match(/\?./)) {
// do not allow access
}
You might need to extend this, depending on other URL's that you need to forbid access to.

History API and domain-level urls

I have two pages on MyDomain.com. The index view which is visible from MyDomain.com/ and MyDomain.com/Foo/Bar. Each view has an ajax call to the other and each one pushes the state using the HTML5 History API.
There are the steps that create the problem:
Start at MyDomain.com/ (Works as expected.)
Click the ajax link to MyDomain.com/Foo/Bar/ (Works as expected.)
Click the ajax link to MyDomain.com/ (Works as expected.)
Click the ajax link to MyDomain.com/Foo/Bar/
Now the URL appears as MyDomain.com/Foo/Foo/Bar/
I don't want a Foo Foo Bar.
My current workaround is to add "../../../" to the front of the URL, but this is inelegant and not foolproof. Another option is a regex expression to count the directory levels.
Is there a better way to get absolute URLs with the History API?
function push(updateElementID, controller, action, url)
{
if (typeof url == "undefined")
{
url = "/" + controller + "/" + action;
}
var state = {
id: updateElementID,
controller: controller,
action: action
}
history.pushState(state, null, url);
}
You may want to ensure that the base element of the href element in the DOM is cleared...at least in the following case, it works for me: On your shared layout page (_layout.cshtml), reset the absolute URL within the DOM by placing the following within the head tags:
<base id="htmldom" href="http://localhost:59805/"/>
of course replacing your port # and on launch, replacing the root URL to the actual domain name.
By doing this, you are setting, or resetting the href property and specifying a base URL for all other relative URLs.
Now would doing it this way would affect any user-input data preserved in the page between back and forward buttons? I'm guessing it would be fine, as the above only resets the href property, and any other info in the DOM should be there.

Javascript bookmarklet to take info from one page and submit it to form on another page

Now that I discovered here that I can't write JavaScript within one page to enter form data on another external page, I'd like to do this with a browser-based bookmarklet instead.
I'm able to access the data on my original page with this bookmarklet code snippet:
javascript:var%20thecode=document.myForm.myTextArea.value;
If I open the external Web-based form manually in the browser, this code changes what's in the text box:
javascript:void(document.externalForm.externalTextArea.value="HELLO WORLD"));
And this bookmarklet code will open a new browser window with the external form:
javascript:newWindow=window.open("http://www.url.com","newWindow");if(window.focus){void(newWindow.focus());}
However, when I try to put these snippets together in a single bookmarklet to open the external form in a new window and change the data inside, I can't access any of the elements in newWindow. For example, this doesn't work to check the existing value of the text area in the new window
javascript:var%20newWindow=window.open("http://www.url.com","newWindow");if(window.focus){void(newWindow.focus());}window.alert(newWindow.document.externalForm.externalTextArea.value);
Once I use the bookmarklet code to open the new window as newWindow, I don't seem to be able to access the elements within that new window. Any suggestions what I'm missing? Thanks.
That's because the bookmarklet runs within the sandbox (the environment) of the current web page. Since you're not allowed to access (the DOM of) another page which doesn't have the same protocol, domain name and port, you're not able to access the document property of newWindow when protocols, domains and ports don't match. BTW, the same is true for accessing iframes on a page.
As you're talking about an “external form”, I guess you don't stay on the same domain. The other examples retrieve or manipulate data on the current page (at that moment) and won't error out.
Also see Same origin policy.
Update: About the Delicious (et al.) bookmarklet: its code actually reads:
(function () {
f = 'http://delicious.com/save?url=' + encodeURIComponent(window.location.href) + '&title=' + encodeURIComponent(document.title) + '&v=5&';
a = function () {
if (!window.open(f + 'noui=1&jump=doclose', 'deliciousuiv5', 'location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550'))
location.href = f + 'jump=yes'
};
if (/Firefox/.test(navigator.userAgent)) {
setTimeout(a, 0)
} else {
a()
}
})()
So, yes, the parameters are only transferred using a GET request.

Categories