Session Storage Not Updating in Safari

I have a text input field in a components html:

<input type="text" (input)="myFunc('test', $event.target.value)">

This hits a function inside a component. The function calls a session storage service, which results in sessionStorage.setItem(key, val)

As you type, the value in session storage is updated to reflect the change. This works perfectly fine in Chrome, however in Safari, it only ever stores the first character typed. The same thing happens with a (click) event, it will give the key a value, but on the subsequent click, the value should (and does in Chrome) change, but does not change from the initial value when using Safari.

If I log out the value being passed from the text field inside the function where I set the value, it shows as I expect in both browsers. Just for some reason Safari is not updating.

There are no errors being shown in the console. I am not using either browser in incognito mode.

The component:

export class MyComponent implements OnInit {
  constructor(private sessionStorageService: SessionStorageService) {}
  ngOnInit(): void { }

  public myFunc(key: string, value: any) {
    this.sessionStorageService.set(key, value);
    console.log(value);
  }

The Storage Service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class SessionStorageService {
  sessionStorage: Storage;

  constructor() {
    this.sessionStorage = window.sessionStorage;
  }

  get(key: string): any {
    if (this.isSessionStorageSupported) {
      return JSON.parse(this.sessionStorage.getItem(key));
    }

    return null;
  }

  set(key: string, value: any): boolean {
    if (this.isSessionStorageSupported) {
      this.sessionStorage.setItem(key, JSON.stringify(value));

      return true;
    }

    return false;
  }

  remove(key: string): boolean {
    if (this.isSessionStorageSupported) {
      this.sessionStorage.removeItem(key);

      return true;
    }

    return false;
  }

  get isSessionStorageSupported(): boolean {
    return !!this.sessionStorage;
  }
}

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.