Search code examples
javascriptphpjquerysessionreload

How I can reload all the opened pages of my website when I click a button


Im trying to reload all the opened pages when I change the $_SESSION variables. But trying different approaches I dont now why it does not work. The reason of updating all the pages is because I have a functionality on my page for the admins that allows them works as a virtual user. So all the old session variables are updated and I store the old info. As this already work, my problem now is how I can update this session variables in all my pages. My approach is reloading all the pages but if its other chocice im am glad to hear it. Thanks in advance

What I have in my last try for making all the things work is this:

I have on my event listener with jquery this

$('#virtual_user_data').on('click', function(){
  var user_type = $('#select_user_type').val();
  var user_id = $('#select_user').val();

  $.ajax({
    url: 'include_php/impersonate.php',
    async: false,
    data : {'user_type_id' : user_type, 'user_id' : user_id},
    type : 'POST',
    success : function(data){
      window.postMessage({ type: "reload" }, "*");
      //console.log(message);
      
      if (user_type == 3)
        $(location).attr('href','home_provider.php');
      else if (user_type == 2)
        $(location).attr('href','home.php');
      
    }
  });
});

As I am sending a message to all the pages I create a script called reload.js with this:

$(window).on("message", function(event) {
    if (event.originalEvent.data.type && event.originalEvent.data.type === "reload") {
        location.reload();
    }
});

And finally I included this script to the pages I want to reload (only one for testing) and It does not work


Solution

  • you can try window storage event, It will emitted when your localstorage gets modified

    addEventListener("storage", (event) => {
         // check your storage variable 
         // then reload your page here
    });
    

    Note: This is not work for same page, so this will call only when storage change by some other page

    Thanks, let me know if this will not work