Javascript check if windows

Check if it’s the window object

Given that my plugin could be run on any JS engine (in a browser or not),

How does one know that some variable is actually the browser window object.

Like how do I know if someVar references the browser window object. Is there something in window that I can check if it is really the browser window object?

And how to check if the browser window object actually exists and not just some window variable containing an object.

Suppose you can’t tell if someVar is window by itself, and you want to match it against the real browser window object like someVar === window , how do you get window that you are sure it is the browser window and not some other object from an outer scope named window , or some other global from another environment?

Just to clarify a bit more:

  • I’m not looking for the global of the environment. I’m looking for the browser window object specifically.
  • I’m not checking if the script is running on the browser.

I can’t do something like if(!window) since window could just be another object declared somewhere outside the scope.

I can’t check if(window.window === window) since I can also do self referencing, and like said earlier, window could be an object from an outer scope:

And the following may not work since the script could be wrapped or concatenated within something other than the global space. this could also be modified with calls like call() , apply() or bind() .

I have a feeling that this is a duplicate, but I couldn’t find where I first saw it.

Check if homepage using window.location

Is it possible to check if I’m on the homepahge/index of a site using window.location ?

I’m currently checking url using

but how can I check for homepage? It doesn’t contain any segments.

Note: I don’t know what the homepage URL will be so I can’t use for example a url name like window.location.href.indexOf(«myhomepage.html»)

Читайте также:  Windows кто у кого ворует

Update: The only clue that I have is that the homepage has no URL segments.

4 Answers 4

Many site’s homepage, including stackoverflow contain a link to that same homepage.

If you have access to the source, you can identify this link server-side

So, to check if you are on the homepage:

So i just saw your update to the question. if you know there are no url segments, wouldn’t window.location.pathname always be «/»

The term homepage itself is a fairly vague construct and not something that is technically identifiable. You could have several different landing pages depending on your screen size, device, credentials, browser, date/time, geolocation, etc. etc.

The only way you can ensure you are on one of these landing pages is to be in control during the initial GET request to the domain (e.g. http://www.example.com ).

So, if you’re already on the page, there’s no real way to know how you got there and if this is the default page provided from that domain, though there are hacks you could try to get a general (albeit very error-prone) idea.

For example, you could compile a list of common homepage paths:

Check if object exists in JavaScript

How do I verify the existence of an object in JavaScript?

The following works:

But this throws an Error:

The Error:

18 Answers 18

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

There are a lot of half-truths here, so I thought I make some things clearer.

Actually you can’t accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).

The reason is Javascript has this notorious value of undefined which strikingly doesn’t mean that the variable is not defined, or that it doesn’t exist undefined !== not defined

So both a variable that exists and another one that doesn’t can report you the undefined type.

As for @Kevin’s misconception, null == undefined . It is due to type coercion, and it’s the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null . Of course you can be explicit, because it may help readability.

Читайте также:  Python с библиотеками windows

If you restrict the question to check if an object exists, typeof o == «object» may be a good idea, except if you don’t consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.

The primal area where you really should be careful about typeof , undefined , null , unknown and other misteries are host objects. They can’t be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it’s the only secure way to use a feature that may not even exist.

Check if my website is open in another tab

I want to check with JavaScript if the user has already opened my website in another tab in their browser.

It seems I cannot do that with pagevisibility.

The only way I see is to use WebSocket based on a session cookie, and check if the client has more than one socket. But by this way, from current tab, I have to ask my server if this user has a tab opened right next to their current browser tab. It is a little far-fetched!

Maybe with localstorage ?

3 Answers 3

Using local storage I created a simple demo that should accomplish what your looking to do. Basically, it simply maintains a count of currently opened windows. When the window is closed the unload events fire and remove it from the total window count.

When you first look at it, you may think there’s more going on than there really is. Most of it was a shotty attempt to add logic into who was the «main» window, and who should take over as the «main» window as you closed children. (Hence the setTimeout calls to recheck if it should be promoted to a main window) After some head scratching, I decided it would take too much time to implement and was outside the scope of this question. However, if you have two windows open (Main, and Child) and you close the Main, the child will be promoted to a main.

Читайте также:  Windows admin hack как пользоваться

For the most part you should be able to get the general idea of whats going on and use it for your own implementation.

Oh yeah, to actually see it in action. Open the link in multiple windows. 🙂

Update:

I’ve made the necessary changes to have the the local storage maintain the «main» window. As you close tabs child windows can then become promoted to a main window. There are two ways to control the «main» window state through a parameter passed to the constructor of WindowStateManager. This implementation is much nicer than my previous attempt.

Javascript: Check if this window is already opened

I am trying to detect whether the current page is already opened in a different tab or not.

I tried using window.open(), but I get as return the current window itself, not the supposedly other window of same address. It will always return true.

So say, if ‘mysite.com’ is already opened, when the user opens a new window with ‘mysite.com’, I shall detect that, focus the other window and close the current one.

Would love to hear any ideas, or whether this is possible. I’m trying to capture all links into a single tab.

2 Answers 2

You can use localStorage events to communicate between different tabs and therefore detect if a page is already opened. Check this answer: https://stackoverflow.com/a/14792159/60745

Even when you’re only concerned with a tab in the same browser on the same machine, the problem with trying to accomplish this through pure javascript is that although you could set a cookie on each of your sites pages ( window.onload ) to record the user has initially visited your site, there’s no safe way to ensure you remove this cookie when they leave.

Although you have the onunload & onbeforeunload events, these are not fired when you leave a site over a link, uses a browsers back button or closes the browser.

Not the answer you’re looking for? Browse other questions tagged javascript or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Оцените статью