How to append parameters to URL before page starts loading? - javascript

In Chrome, I'm looking to detect in a page URL is going to be on example.com's domain, and if it is, before loading, append foo=bar as a parameter and load that instead.
I've found that I can access when the Omnibar has been submitted here, but it seems like it'd load the original URL anyways, and while that's alright it's twice the bandwidth I feel is necessary. It's not a problem when it's only one page, but it's a change that needs to happen on every page in an site, so double the bandwidth definitely becomes an issue.
Currently, it works to detect if the URL is going to be example.com and is submitted, then call window.stop() and then set location.href to example.com/&?foo=bar but that doesn't seem ideal.
In short, the user goes to http://www.example.com and then the script changes it to http://www.example.com/&?foo=bar before loading the original link.

Take a look at the chrome.webRequest API, in particular the following method:
onBeforeRequest (optionally synchronous)
Fires when a request is about to occur. This event is sent before any TCP connection is made and can be used to cancel or redirect requests.

You can use
window.location.search = "foo=bar"
may be this helps.

Related

Handling ajax URLs from different pages?

So I have my site at http://example.com/foo/ (under a directory, the main domain is for something else).
Using .htaccess, I've set up my pages so the URLs look like http://example.com/foo/about/, http://example.com/foo/polls/, http://example.com/foo/registration/, etc. This works great and the site loads fine and can be traversed without any Javascript issues.
Now, I'd like to add some AJAX functionality to the navigation. If I'm on http://example.com/foo/ and I click the navigation for "About", it changes the URL to http://example.com/foo/#about and dynamically loads the about page in one section of the site. I also have this working.
I have two problems which involve handling switching between AJAX and non-AJAX URLs.
If I'm on http://example.com/foo/about/ and I click on polls, it would look like http://example.com/foo/about/#polls which doesn't look very pretty. Ideally, I'd want every AJAX URL to be formatted with just the main directory and a hash, like http://example.com/foo/#about.
Should I handle it by forcing an actual (non-AJAX) redirect to the index page with a hash symbol then load it from there?
The other problem is the reverse. If I send http://example.com/foo/#about to someone who has Javascript disabled, or maybe if someone links to it and a bot crawls that link, is there any way to handle that to redirect to the correct non-AJAX page or is this just an unfortunate fact of life I'll have to deal with?
If you need non-javascript support, I'd change all your urls directly to the pages. Like http://example.com/foo/#about to http://example.com/foo/about/
Then, the javascript can intercept it, call event.preventDefault(), and 'redirect' it to #about, which will follow your ajax functionality.
If the client doesn't have javascript, it will go to http://example.com/foo/about/ as normal.
As for being on http://example.com/foo/about/, a javascript client should never get here as they will always be redirected to hashtags.
1) if you redirect to the main page and then use ajax to load the about page that would just not make much sense. what you should do is make everything work through ajax : there should never be a http://example.com/foo/about/ in the first place only http://example.com/foo/#about then you just update the hash and the content when you click on polls.
2) there is no way to avoid, sorry.

On click, redirecting to another URL if server slow?

Is it possible (in Javascript, ajax, other e.g. on the client site) to redirect the user to another URL if first URL slow to answer (when he clicks on a link) ?
A href=URL1 but if no answer from server1 after 1 second, redirection to URL2 (another server)
I was thinking about something like on event onclick :
redirection to URL1, timer, redirection to URL2 but if server 1 is not responding, the code after won't be executed...
Or then using AJAX, but I don't see how
The case ; a click on a page (a href=urltracking), urltracking redirect to URL2, but urltracking server can be slow...
I'm afraid it's not possible in this way. You can measure the response time by "timeout check" with a dummy AJAX call, if the target URL lays in your domain. Something like "send test GET, if server doesn't respond in XX secs then rewrite URLs to backup sites". But it's not suitable for general use.
Are both these sites your own? Maybe you should buy a load balancer. This is essentially a server that monitors performance of two webservers and redirects requests to the one that is least busy.
I always try to avoid situations where a 3rd party site can slow down my own site.
Perhaps you can make the call in some asynchronous form instead? Have a piece of javascript fire within the DOM ready event that makes the call to the tracking server instead, something like (in jQuery):
$(function(){
var tracker = new Image();
tracker.src = "http://tracker.com/path/to/tracker
});
other methods that can work are just a plain old tag, or an , etc. The key being that this loads after your page, and not before it. The tracking server will never know the difference.
Pay more money for a better server(s) and in extreme case with a load balancer. You should never need to do something like this client side.
You can use setTimeout Function of javascript.
setTimeout("function()",1000);
here in function you need to write code for redirection.
Also see this question for complete reference.
Correct me if I am wrong.

Accessing URL executes JavaScript

I've coded an HTML page using jQuery for loading content. Now if I want to link directly to a submenu, is this possible to do with JavaScript?
So for example if someone goes to www.mydomain.com/submenu1/
then some JavaScript code will execute and load the needed contents?
Thanks a lot :)
Is it possible to realize that with htaccess?
You will more likely want to have a URL structure that only needs a page to load from the server once, then the server is only queried by JavaScript XMLHttpRequests. Loading content based on a "hard" URL would be pointless, since you're doing a server request anyways and might as well return the content in the response.
For keeping addresses unique while still keeping the "hard" URL the same (preventing multiple server requests), you can use the hash/anchor part of the URL. This means your address might look something like this: http://www.example.com/#/submenu1/
The #/submenu1/ part stays on the client, so only / on www.example.com is requested. Then it's up to your JavaScript to load the content relevant to /submenu1/. See a page of mine for an example of this: http://blixt.org/js#project/hash?view=code
Also have a look at this question: Keeping history of hash/anchor changes in JavaScript

Javascript: onrefresh or onreload?

I want an event handler that fires when the user hits reload. Is onrefresh or onreload the correct handler to add to ? Also, will this even fire before or after onunload? Are there an browser inconsistencies? Thanks.
I don't think there are events called onrefresh or onreload. You can know when the page is unloading, but knowing why (i.e. where the user is going next) is outside JavaScript's security sandbox. The only way to know whether the page has been reloaded is to know where the user was on the last page request, which is also outside the scope of JavaScript. You can sometimes get that via document.referrer, but it relies on the browser's security settings to permit access to that information.
The WindowEventHandlers.onbeforeunload event handler property contains the code executed when the beforeunload is sent. This event fires when a window is about to unload its resources.
window.onbeforeunload = function () {
return 'Are you sure you want to leave?';
}
This will show a confirm dialog to the user with the message you returned in your function. It will give the user a leave this page or cancel option.
There is no way around the confirm as it could be used for malicious reasons.
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
If you combine setting a cookie with a for the specific page, with a check for the onload event, you can simulate the nonexistent event you seek. You might adjust the cookie expiration so that a reload is counted only if the initial onload was a certain time interval ago.
There are no onreload or onrefresh events that I'm aware of. Certainly from javascript running in a browser this make little sense. The existing window and all its contents are effectively discarded. Hence you either need to use onunload of the existing context or the load event of the new context that is created as result of reload.
I do believe artlung may have indeed found a way, actually... his version, however, relies on cookies, and those can be cut off from use in numerous ways; the solution, then, is to use a server-side language of your choice to save the timestamp of when the page is unloaded via JavaScript (still a vulnerability, yes, but why not throw another idea out there, huh?) and then testing it again upon every page load; if you detect a difference of less than a few seconds, the user probably just reloaded your page. : )
could use a session. easier than a cookie and don't have to worry about expiration or database. That would cover you for any page except the first one. I don't think the session superglobal is available til the second page. If that's a problem, you could start a session and reload the page immediately if there is no active session.
its onunload
because when you hit refresh the browser "unloads" then loads again

What's the best way to automatically redirect someone to another webpage?

I've never learnt JavaScript, but I imagine this is quite a simple problem. Just wanted to know which method is most advised these days.
// use this to avoid redirects when a user clicks "back" in their browser
window.location.replace('http://somewhereelse.com');
// use this to redirect, a back button call will trigger the redirection again
window.location.href = "http://somewhereelse.com";
// given for completeness, essentially an alias to window.location.href
window.location = "http://somewhereelse.com";
edit: looks like the user who posted the better answer has left SO, i've consolidated his answers here.
Most advised? To not do it. HTTP is far better suited to the job than JavaScript is (search engines follow them, you can state if it is permanent or not, they are faster, etc).
Failing that…
If you want an immediate redirect:
window.location.replace('http://example.com/');
This will replace the current URI with the new URI in the browser history, so the back button won't land the user on a page that immediately throws them forward again.
If you don't really want to redirect, but want to send the user somewhere in response to an event:
window.location.href = 'http://example.com/';
Remember to have a non-JavaScript fallback. A link is usually the best option, but it does depend on context.
Time delayed redirects are an even worse idea. The only reason to use them is if you want to display a message to the user - and users read things at different speeds (and have them sitting in another tab while they do something else). If the message is important enough to show, then it should be important enough to leave on screen until the user has read it and clicked a link to the next page.
One important thing to remember when redirecting a page using JavaScript is, always provide a non-JavaScript redirect as well! A link would do, or better a <META> tag, for example: <meta http-equiv="refresh" content="2;url=http://example.com">
These days, I think the most advised method is not to do javascript (or meta) redirects. Do you really need it ? Could you use a redirect HTTP header instead ?
The W3C's Web Content Accessibility Guidelines (7.4) also discourage the creation of auto-refreshing pages, since most web browsers do not allow the user to disable or control the refresh rate

Categories