Can I look up the user agent from JavaScript? - javascript

We know it's possible to look up the IP of a visitor using JSON and a callback, as seen here Can I perform a DNS lookup (hostname to IP address) using client-side Javascript? and also at http://news.ycombinator.com/item?id=1896015 - but what about a similar thing for the user agent?

This string is directly available in navigator.userAgent. However, this string is not very reliable, because the user can easily modify it. Only use it for non-critical purposes.
If you want to detect the user agent, so that you "know" what's supported, you'd better switch to capability-detection.
Examples of alternative methods to detect the browser:
IE: Conditional comments (HTML (also includes IE version) or in JScript)
Firefox / Webkit / Opera: Setting a CSS property with a vendor-prefix, and checking for the existence of the just-set property.

navigator.userAgent contains the user agent string of the browser.

Related

Parse host from url without subdomains etc

I'm working on a chrome-extension that reads the domain from window.location.hostname. Now for this extension to work properly, I need to be able to separate subdomains and other url variation to the same host. example:
I need all of the following url:s
www.google.com
accounts.google.com
photos.google.se
example.google.co.uk
https://google.com
all of these need to be resolved to, in this case, "google", in a way that is reliable and will work for any website with sometimes quirky subdomainconfigurations.
this is my current aproach, somewhat simplified:
var url = window.location.hostname.split(".") //returns an array of strings
for(i=0;i<url.length;i++){
if(url[i].match(domainregex) //regex for identifying domains ".com",".se",".co.uk" etc
return url[i-1] //usually what I'm after is directly before the domain, thus i-1
}
This approach is alot of hassle, and has proven unreliable at times...Is there any more straitforward way of doing this?
A more reliable solution to strip the top level domain part and get the main domain part is to use Public Suffix List which is used by Firefox and Chrome and other browsers.
Several js parsers of the list data are available if you don't want to write your own.
I had to do it for my fork of edit-my-cookies, so It will able to change profile of cookies per site. (https://github.com/AminaG/swap-my-cookies-multisite/blob/master/js/tools.js)
It is what I did, and it is working for me. I am sure if it not complete solution, but I am sure it can helps.
var remove_sub_domain=function(v){
var is_co=v.match(/\.co\./)
v=v.split('.')
v=v.slice(is_co ? -3: -2)
v=v.join('.')
console.log(v)
return v
}
it is working for:
www.google.com
accounts.google.com
photos.google.se
example.google.co.uk
google.com
if you want it to work also for:
http://gooogle.com
You first need to remove the protocol:
parser=document.createElement('a');
parser.href=url;
host=parser.host;
newurl=remove_sub_domain(host);

local storage see how much space each domain is using

After going through specification on HTML5 Storage: http://www.whatwg.org/specs/web-apps/current-work/multipage/webstorage.html#event-storage
In the paragraph 11.3 Disk space I have read that
User agents should allow users to see how much space each domain is
using.
But there is no information on how I can do this.
The only solution I came up with - is a hack like this:
JSON.stringify(localStorage).length
Is there a normal way to do it, because in my case you can see just one domain, not each domain.
An no one gave any response, I will be additing my own answer with whatever information I will find.
JSON.stringify(localStorage).length approximate number works for every browser
IE:
can be used through JS: window.localStorage.remainingSpace
Chrome:
through Settings>Content Settings>Cookies & Site data

Change url via JavaScript (no hash-tag)

I'm wondering how does facebook change the url when I switch between pictures in a album? There is no hash-tag, just a real url.
Example:
The current url: facebook.com/photo.php?fbid=XXXXXX1 and if I click next, the url changes to facebook.com/photo.php?fbid=XXXXXX2
Does anybody know how to realize this with JavaScript?
Yes. Check out https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
It pushes a new history state (an HTML5 thing) instead of using the hash key.
My first hunch would be:
document.location = facebook.com/photo.php?fbid=XXXXXX2;
With some way of preventing the default reload page action.
Summerizing all the answers,
we can say (I'm not a FB coder) that Facebook uses:
the HTML5 window.history.pushState / replaceState / popState methods on browser that support these methods (I think one is Chrome). In this way Facebook changes the real url (not just the part after the # character).
On other browsers, that do not support these new HTML5 methods (like IE6 / IE7 and IE8), Facebook simply changes the part of the url after the # character, by simply setting the the window.location.hash property.
On my tests, it only changes the hash tag:
E.g. the real URL is:
http://www.facebook.com/photo.php?fbid=x&set=z
and clicking next results in:
http://www.facebook.com/photo.php?fbid=x&set=z#!/photo.php?fbid=y&set=z&pid=pid&id=id
The part after the hash is setup for Google AJAX crawl. But for the purpose of the browser, it's just a hash (fragment identifier).

Detect if javascript is enabled in a winforms/mfc embedded browser

I have a native (windows) application that has an embedded web browser. Currently I'm invoking a javascript function from the backend (c++/c#). However, if javascript is disabled this fails and I'd like to provide a fallback mechanism. Is there a way to determine if javascript is disabled?
In the IE Web Control, you can simply force JavaScript on. Please refer to the following interfaces, which your host has to implement:
IDocHostUIHandler
IDocHostShowUI
IInternetSecurityManager
IServiceProvider
Another approach would be for your HTML page to query the window.external object and call a method on it, which you implement in your host, which sets a flag to true. Not being called would mean the JavaScript was not executed.
Wow, using web browser under mfc is really pain in the ass, you can do it by getting the IInternetSecurityManager, and check if is enabled to execute javascript by current policy, if user select to disable javascript on his IE, you will need to overwrite the value in the registry.
HRESULT hr = CoCreateInstance(CLSID_InternetSecurityManager, NULL,
CLSCTX_INPROC_SERVER,IID_IInternetSecurityManager, (void**)&pSecurityMgr);
int policy = URLPOLICY_ALLOW;
hr = pSecurityMgr->ProcessUrlAction(L"http://www.google.com", URLACTION_SCRIPT_RUN,
(BYTE*)&policy, sizeof(policy), NULL, 0, PUAF_TRUSTED, 0);
if hr = S_FALSE, javascript execution is disabled...

Is it the filename or the whole URL used as a key in browser caches?

It's common to want browsers to cache resources - JavaScript, CSS, images, etc. until there is a new version available, and then ensure that the browser fetches and caches the new version instead.
One solution is to embed a version number in the resource's filename, but will placing the resources to be managed in this way in a directory with a revision number in it do the same thing? Is the whole URL to the file used as a key in the browser's cache, or is it just the filename itself and some meta-data?
If my code changes from fetching /r20/example.js to /r21/example.js, can I be sure that revision 20 of example.js was cached, but now revision 21 has been fetched instead and it is now cached?
Yes, any change in any part of the URL (excluding HTTP and HTTPS protocols changes) is interpreted as a different resource by the browser (and any intermediary proxies), and will thus result in a separate entity in the browser-cache.
Update:
The claim in this ThinkVitamin article that Opera and Safari/Webkit browsers don't cache URLs with ?query=strings is false.
Adding a version number parameter to a URL is a perfectly acceptable way to do cache-busting.
What may have confused the author of the ThinkVitamin article is the fact that hitting Enter in the address/location bar in Safari and Opera results in different behavior for URLs with query string in them.
However, (and this is the important part!) Opera and Safari behave just like IE and Firefox when it comes to caching embedded/linked images and stylesheets and scripts in web pages - regardless of whether they have "?" characters in their URLs. (This can be verified with a simple test on a normal Apache server.)
(I would have commented on the currently accepted answer if I had the reputation to do it. :-)
Browser cache key is a combination of the request method and resource URI. URI consists of scheme, authority, path, query, and fragment.
Relevant excerpt from HTTP 1.1 specification:
The primary cache key consists of the request method and target URI.
However, since HTTP caches in common use today are typically limited
to caching responses to GET, many caches simply decline other methods
and use only the URI as the primary cache key.
Relevant excerpt from URI specification:
The generic URI syntax consists of a hierarchical sequence of
components referred to as the scheme, authority, path, query, and
fragment.
URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
hier-part = "//" authority path-abempty
/ path-absolute
/ path-rootless
/ path-empty
I am 99.99999% sure that it is the entire url that is used to cache resources in a browser, so your url scheme should work out fine.
The MINIMUM you need to identify an HTTP object is by the full path, including any query-string parameters. Some browsers may not cache objects with a query string but that has nothing to do with the key to the cache.
It is also important to remember that the the path is no longer sufficient. The Vary: header in the HTTP response alerts the browser (or proxy server, etc.) of anything OTHER than the URL which should be used to determine the cache key, such as cookies, encoding values, etc.
To your basic question, yes, changing the URL of the .js file is sufficent. TO the larger question of what determines the cache key, it's the URL plus the Vary: header restrictions.
Yes. A different path is the same from the caches perspective.
Of course it has to use the whole path '/r20/example.js' vs '/r21/example.js' could be completely different images to begin with. What you suggest is a viable way to handle version control.
depends. it is supposed to be the full URL, but some browsers (Opera, Safari2) apply a different cache strategy for urls with different params.
best bet is to change the name of the file.
There is a very clever solution here (uses PHP, Apache)
http://verens.com/archives/2008/04/09/javascript-cache-problem-solved/
Strategy notes:
“According the letter of the HTTP caching specification, user agents should never cache URLs with query strings. While Internet Explorer and Firefox ignore this, Opera and Safari don’t - to make sure all user agents can cache your resources, we need to keep query strings out of their URLs.”
http://www.thinkvitamin.com/features/webapps/serving-javascript-fast
Entire url. I've seen a strange behavior in a few older browsers where case sensitivity came into play.
In addition to the existing answers I just want to add that it might not apply if you use ServiceWorkers or e.g offline-plugin. Then you could experience different cache rules depending on how the ServiceWorkers are set up.
In most browsers the full url is used.
In some browsers, if you have a query in the url, the document will never be cached.

Categories