How to check if a web page is open or not?

Viewed 39

I have a website where users message each other through another website. My problem is that everytime user click on message item this action opens a new tab.

Having a lot of conversations makes this quite annoying, especially when using on a smartphone.

Is there any way to check if the website for texting is open?

2 Answers

You are looking for postMessage. Synapsis:

postMessage(message, targetOrigin, transfer)
  • message is the actual message you want to send
  • targetOrigin specifies which domain is the target
  • transfer is a sequence of transferrable objects that are transmitted with the message

So, what you really want is to have this conversation:

  • Page1: are you there?
  • Page2: yes

or

  • Page1: are you there?
  • ... (timeout)

I will call Page2 the page whose existence we wonder about and Page1 the page which wonders about Page2's existence.

First of all, you need a message handler at both Page1 and Page2. Synapsis:

window.addEventListener("message", (event) => {
  if (event.origin !== "http://example.org:8080")
    return;

  //check event.data and see what happens
}, false);

On Page 2, your message handler will need to check whether the message asks about its existence and calls postMessage('Yes, I am here', event.origin); if so. Page1, on the other hand initiates the messaging by calling postMessage('Are you there?', theurl); (where you need to replace theurl with your value). Now, Page1 expects a message. If the message arrives, then Page2 exists. If not, then after a timeout you need to handle the nonexistence of Page2. So, you will have something like this at Page1:

var wasFound = false;
postMessage('Are you there', theurl);
setTimeout(function() {
    if (!wasFound) {
        //The page needs to be opened
    }
}, 500);

Naturally, you will need to set wasFound to true when you receive a message from Page2 and you will need to make sure that the message handler sees the same wasFound variable that your timeout checks for.

If you are using window.open() you can add the target parameter.

A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special target keywords, _self, _blank, _parent, and _top, can also be used.

example

window.open("https://www.mozilla.org/", "mozillaTab");
Related