Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to continuously messaging popup with postMessage() to control state

I have a site that can be displayed in one of two states (let's say normal and debug). In most scenarios, pages on this site will be displayed in the normal state - however there are some instances where this page will be opened as a popup and needs to be displayed in the debug mode.

I am currently achieving this as follows:

JS on the page being loaded listens for a message with:

window.addEventListener("message", enterDebugMode, false);

And if the appropirate message is sent, debug mode is entered.


The problem: If the user navigates to a new page (on the same site) in that popup window the new page will have no idea that it is supposed to display in debug mode as the previous original page that the popup loaded recieved the message, but the subsequent page(s) don't recieve that message.

The hacky solution: Keep sending the message repeatedly (i.e. every 1sec) to ensure that any new pages receive the message and enter debug mode. If a page is already in debug mode it ignores any subsequent messages.


I really don't like having to continuously message the page, though, and would rather a cleaner and more efficient solution if one exists. One such idea would be to send a new message if the popup loads a new page, but unfortunately I can't register any event handlers to listen for a page load event as this is a cross-origin operation.

I could also have the page being loaded message the parent to see if it should be in debug mode - but I don't want the page being loaded to be initiating any communication - the first message should originate from the parent.

like image 454
abagshaw Avatar asked Sep 02 '17 20:09

abagshaw


Video Answer


2 Answers

Have you thought about local storage?

Something like

function setupDebug() {
    // do whatever awesome debug stuff you need to do
}

function enterDebugMode() {
    window.localStorage.setItem("debug", true);
    setupDebug();
}

window.addEventListener("load", function () {
    if (window.localStorage.getItem("debug")) {
        setupDebug();
    }
}, false);

function leaveDebugMode() {
    window.localStorage.removeItem("debug");
    // Turn off the debug stuff
}
like image 199
Moose Morals Avatar answered Oct 28 '22 19:10

Moose Morals


You can pass an argument in the provided URL, just by appending '#debug' or '?debug=on'. Sites usually ignore this.

At the load event you can ask for location.hash or location.search, depending on what you use. Be aware that the change of the search string usually causes a reload and the hash not.

You might have to go through document.links to make this work. May be an 'onhashchange' event handler can be useful too.

like image 1
gnblizz Avatar answered Oct 28 '22 20:10

gnblizz