web development – Options to notify users Single Page Application (SPA) static resources have updated if users don’t refresh their browsers

I need to design a way to notify my user the SPA has updated if they don’t refresh their browsers, i.e. if no requests to get index.html is made after the initial load, how do I notify users the javascript or css files have updated on the server? Note, it is not the REST api that my SPA communicate with updates but the SPA’s static resources.

I think the options are limited:

  1. Start a time to keep querying the latest version number
  2. Add a customer header field about the latest version in responses for most if not all XHR requests SPA send
  3. using websocket to notify SPA
  4. I am not familiar with service worker but I read articles about it may work too.

There is another problem I need to deal with, my SPA is deployed on its own server, which is separated from the REST server it communicates with(although I suspect it is common) and there are cases that the SPA has new versions while REST server doesn’t. The version number I design should be able to tell these 2 cases.

I notice folks asked this kind of questions on stackoverflow many times. I can find more 10 questions, with the earliest one I found in 2013 and the latest one in 2019. I list some here.

  1. How to handle expired files without refreshing the browser when using Single Page Application (SPA)?
  2. How to force update Single Page Application (SPA) pages?
  3. How can I force SPA clients to hard refresh if there is a new build?
  4. Refreshing a cached Angular SPA
  5. Proper way to refresh Single Page Application

The reasons I asked here are:

  1. I like to design a build process to update the SPA version automatically. Manually update the version number is error prone. None of answers seem to address this.
  2. All those Q&A on SO seemed to failed to mention the case that the SPA server and REST server is separated and what I need here is an update for SPA files. For example if I use the option 2, adding a customer header field in response I need to differentiate the SPA version and REST api version. None of the answers I saw address this. Some answers just focus on REST api version update.
  3. I believe this question should be address by a build process, a communication process and maybe a deploy model. So this is a question about SPA architecture.
  4. The mere facts that this question has been asked so many times for 8 years probably has said it clearly that there is no easy answer for it, probably even without some best practices. Some answers failed to realize is the core issue here is to retrieve index.html so focus on cache busting, file naming or setting Cache-Control, like this one How to force the browser to reload cached CSS and JavaScript files

php – Mobile detect directive only works after first refresh

I am trying to detect mobile devices and send them to a different directory on my server. The desktop version of the website is a WordPress website; the mobile version is HTML. At the moment, the mobile website only loads if I refresh the page. The first load seems to come from the browser cache but this issue persists even after I clear the browser cache.

I am using this Mobile-detect library mobile detect library to detect if the device requesting the page is mobile and redirecting the visitor with PHP header(Location: ...).

In the root of my server, I’ve got:

// website structure for mywebsite.com
/public_html 
    /lib
        /mobile-detect.php // the mobile detect 3rd-party library
    /m // the mobile website version
        /index.html
        /index.html.bak.bak
    /wp-admin
    /wp-content
        /themes/
            my-child-theme/
    /wp-includes
    etc...

Inside the header.php file in my child theme, I’ve tried the following:

<?PHP
    // at the top of the page
    require_once 'lib/mobile_detect.php';
    $detect = new Mobile_Detect;
    if ( $detect->isMobile() ) {
        header('Location: https://mywebsite.com/m/');
        exit;
    }
?>

I tried expanding that with more directives related to caching:

<?PHP
    // at the top of the page
    header("Cache-Control: max-age=0, no-cache, no-store, must-revalidate"); //from amclin

    require_once 'lib/mobile_detect.php';
    $detect = new Mobile_Detect;
    if ( $detect->isMobile() ) {
        header('Location: https://mywebsite.com/m/');
        exit;
    }
?>

I’ve tried adding meta tags to the <head> of the document after the PHP code:

<meta http-equiv=“Expires” content=”-1″>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

And I’ve tried using Javascript in addition to all the rest of it:

<script type="text/javascript">
    if (screen.width <= 699) {
        document.location = "https://mywebsite.com/m/";
    }
</script>

The original example from the 3rd party mobile-detect library recommended using Cookies here but I have to admit, I didn’t understand the logic of it. I tried it originally but had the same issue:

<?php
    @include('lib/mobile_detect.php');
    $detect = new Mobile_Detect();
    if ($detect->isMobile() && isset($_COOKIE('mobile'))) {
        $detect = false;
    }
    elseif ($detect->isMobile()) {
        header('Location:https://gorgepointepub.com/m/');
    } 
?>

The index.html page inside public_html/m/ contains this:

<?php
setcookie('mobile','m',time()+3600,"https://wordpress.stackexchange.com/",'mywebsite.com/');
echo @file_get_contents('index.html.bak.bak');

I also tried adding caching directives to this file:

I also tried using wp_redirect in place of header():

<?PHP
    // at the top of the page
    require_once 'lib/mobile_detect.php';
    $detect = new Mobile_Detect;
    if ( $detect->isMobile() ) {
        wp_redirect('Location: https://mywebsite.com/m/');
        exit;
    }
?>

The WP site uses Clearfy Caching plugin. I’ve cleared the cache on that time and again.

So I’m clearly working at the wrong level for this and am curious what’s going on here.

Why is the browser getting the desktop version first and then, after refreshing the page, going to the server and getting a fresh header.php file? Is this code in the wrong place? Should it be in an index file somewhere else? Do I need to use cookies for this? Aggghhhh!

Thanks for your help on this!

magento2.4.1 – Add product to Wishlist without redirecting and without refresh using ajax

My controller:

appcodeHeartListcolorControllerIndexWishlist.php

<?php

namespace HeartListcolorControllerIndex;

class Wishlist extends MagentoFrameworkAppActionAction {

    public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoWishlistHelperData $wishlistHelper,
        MagentoFrameworkControllerResultJsonFactory $jsonFactory
        ) {
            parent::__construct($context);
            $this->wishlistHelper = $wishlistHelper;
            $this->jsonFactory = $jsonFactory;
    }

    public function execute() {
        $result = $this->jsonFactory->create();
        $data = $this->wishlistHelper->getWishlistItemCollection()->getData();

        return $result->setData(('status' => 200, 'items' => $data));
    }

    
}

appcodeHeartListcoloretcfrontendroutes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route frontName="customwishlist" id="customwishlist">
<module name="Heart_Listcolor"/>
</route>
</router>
</config>

Now the product added but redirect to the wishlist landing page, how to add the product to Wishlist without redirecting and without refresh using ajax

My custom theme Magento_Wishlist

appdesignfrontendZeromy_themeMagento_Wishlisttemplatescatalogproductlistaddtowishlist.phtml

<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

/** @var MagentoWishlistBlockCatalogProductProductListItemAddToWishlist $block */
?>
<?php if ($block->getWishlistHelper()->isAllow()) : ?>


<a href="#"
class="action towishlist"
title="<?= $block->escapeHtmlAttr(__('Add to Wish List')) ?>"
aria-label="<?= $block->escapeHtmlAttr(__('Add to Wish List')) ?>"
data-post='<?= /* @noEscape */ $block->getAddToWishlistParams($block->getProduct()) ?>'

role="button">
<!-- data-action="add-to-wishlist" -->
<img class="whislist-icon product-id-<?php echo $block->getProduct()->getId();?>" src="<?php /* @escapeNotVerified */ echo $block->getViewFileUrl('images/whislist.png'); ?>" />
<span><?= $block->escapeHtml(__('Add to Wish List')) ?></span>
</a>

<?php endif; ?>
<?php
$_objectManager = MagentoFrameworkAppObjectManager::getInstance();
$storeManager = $_objectManager->get('MagentoStoreModelStoreManagerInterface');
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
$img = $mediaUrl."yt.png";
?>
<script>
require(('jquery'), function($){
jQuery.ajax({
url: '<?php echo $this->getUrl('customwishlist/index/wishlist') ?>',
method: 'get',
dataType: 'json',
success: function(data) {
var wislistAddesCheckData = data;
var itemLenth = wislistAddesCheckData.items.length;
for(i=0;i<itemLenth; i++){
var wislistAddedProductId = wislistAddesCheckData.items(i).product_id;
$(".product-id-"+wislistAddedProductId).attr('src','<?php echo $img; ?>');
}
}
});
});
</script>

Is it possible to make autoindex module self refresh?

Hello,
I woud like to ask, if it is somehow possible to force autoindex page to refresh automaticlly (for example each 5 seconds).
The reason I want this is following: I have website, where generatig of index is based on data availability. But unfortunatelly, it takes a while for data to compute and transfer on server. During this time, there is onlyindex of page generated by apache. What I want is to make apache refresh this index of page itselfs until index.html is created and webpage with…

Is it possible to make autoindex module self refresh?

angular 2+ – Is it a good practice to restrict refresh , reload & back navigation of a browser(In some special cases only) ? If yes how can we implement that?

The user can’t be navigated to the previous page when we click on back navigation. In some cases, we are able to navigate when the page is refreshed/reloaded. need to restrict to a couple of pages, not throughout the app.
Actually, I’m using this

        constructor( private location: LocationStrategy){
history.pushState(null, null, window.location.href);  
this.location.onPopState(() => {
  history.pushState(null, null, window.location.href);
});  
}

authentication – Refresh tokens by example using Angular and Spring Boot

I am designing out an app that would have an Angular frontend and Spring Boot (Java) backend.

I was considering (but not married to) the prospect of JWT-based authentication:

  1. User logs in with username and password and submits a form; this form POSTS to, say, /auth/sign-in
  2. A Spring Security filter checks to see if the username and password are valid, and if so, generates a JWT with a reasonable (say, 15 minute) expiry and returns the JWT as a response header
  3. Angular client then reuses this JWT until it expires, at which point, Spring Security will send back a specific 400-level error code which will prompt the Angular frontend to redirect the user to the login page and log back in

This is pretty straightforward to implement, but will be a bad UX for my users (if they have to log back in every 15 minutes).

Instead I’m thinking of something along these lines:

  1. Maintain an in-memory cache of some kind mapping each unique user ID to the last activity timestamp (a timestamp representing the last activity they were doing; basically the last time that user did anything in the app that resulted with a call to the backend being made) –> userActivityMap : Map<User,Date>
  2. Every time the user (via the Angular client) does anything in the app that prompts Angular to make a call to the backend, this user activity map is updated with the current timestamp
  3. User logs in with username and password and submits a form; this form POSTS to, say, /auth/sign-in
  4. A Spring Security filter checks to see if the username and password are valid, and if so, generates a JWT with a reasonable (say, 15 minute) expiry and returns the JWT as a response header
  5. Angular client then reuses this JWT until it expires, at which point, the Spring Security filter that detected it as being expired subsequently consults the user activity map. If the user has been active within the last, say, 15 minutes, then a new JWT “refresh token” is generated for the user and sent back to the Angular client with a specific 400-level error code
  6. The Angular client sees this specific error code and knows to pluck the refresh token off the error response, use the value of that token as the main access token/JWT moving forward, and retries the same command with the new (refreshed) access token

I think I could get this to work, but in my Google searches to find what others have done I was surprised to see a million beginner-level “how to” articles but nothing really concrete for this use case. What are typical solutions for this given stack and the specific scenario at hand? Is my solution close to generally-accepted best practices or did I miss the mark considerably?

csrf – JWT refresh tokens and Double Submit Cookies

I am struggling to implement JWT refresh tokens with the Double Submit Cookies method.

My current set up for a browser based webapp without refresh tokens looks like this:

  • Upon successful login, API server returns JWT with expiry in a httponly cookie
  • Client server intercepts this and creates httponly cookie copying the jwt values from the header (need to do this as using node-fetch)
  • On each page request, client server reads httponly cookie, passing jwt value to page as a csrf variable. Meta tag is populated with this (for ajax to access), and hidden form values also pick up this so that they can also pass up csrf token in submit post requests.
  • Ajax request setup accesses the meta tag and creates a custom Authorization header with Bearer Token set to the csrf value. Upon ajax execution, api server now receives jwt in httponly cookie, and also the bearer token csrf value, and compares for equality.
  • Normal form request passes up form values to client server, where the csrf hidden form value is added to a custom authorization header as a bearer token, and this is passed up to api server, along with http only cookie. Once again, values are compared before access is granted.

So, I think current set up is working well, but I now want to add refresh tokens, to prevent user getting logged out during session. However, I can’t see how to do this whilst following the Double Submit Cookie approach.

I think a refresh token API request would work similarly to above in terms of CSRF. The access token would now be very short lived, so I assume we could drop the csrf requirement for that, and just have csrf token for the longer lived refresh token. That means that the csrf check would only happen on the API refresh token requests (let me know, though, if you think this is problematic. Maybe I need two CSRF token values per page)

With this in mind, I see the following problem for ajax requests.

  • Upon ajax resource request failure due to access token expiry, fire an ajax refresh token request up to api server. Include refresh csrf token value in auth header so it can be compared against refresh token stored in httponly cookie (all very similar to current set up)
  • Following successful refresh request, receive both the new access token , and a new request token in httponly cookies.
  • Ajax Request is now performed with new access token (no csrf check?), and everything goes fine.
  • However, user stays on the same page, and then finally sends another resource request, but once again, the token has expired…
  • This time, the refresh token request will fail as it will attempt to use the old csrf token metadata value to populate the authorization header, and the comparison on the API server will fail.

So the problem is with Ajax requests: there is no opportunity to update the on-page csrf token after a successful refresh token request.

Are JWT refresh tokens broken because of this, or am I missing something in my set up?

magento2 – refresh Shipping Method’s block on checkout page Magento 2

We have a custom checkout field called the city where we have multiples cities. Now I want that when customers select/ change any city, refresh the shipping method block. Same as when we add/change the zip code. I have read all of the blog posts and applied that solution nothing worked for me. I would really appreciate it if anyone can help with this.

This did not work for me. Give an error.

Make Gmail refresh every 30 minutes?

30 minutes is just one example. Basically, is there a way to make the web version of Gmail sync/refresh just every X minutes and not instantly as it seems to be the default?

I find it annoying to see new emails flowing in at any given time and I prefer to work in intervals.

mint.com – How can I configure Mint so that it doesn’t try to refresh some specified bank accounts?

How can I configure Mint so that it doesn’t try to refresh some specified bank accounts?

For example, in the following screenshot, Mint is trying to refresh the MIT FCU bank accounts:

enter image description here

I selected “Hide everywhere” all my MIT FCU bank accounts on https://mint.intuit.com/settings.event?filter=hideaccounts but still Mint is trying to refresh them.