Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
Local storage setItem override - Illegal invocation error

I'm trying to override the localStorage.setItem method to add a disable local storage option for debugging purpose. But I keep having a Illegal Invocation error when using the method.

let originalFunction = window.Storage.prototype.setItem;
window.Storage.prototype.setItem = (keyName, keyValue) => {
    console.log("Override worked ! ")
    let currentState = localStorage.getItem("disableStorage");
    if (currentState === null || keyName === "disableStorage") {
        originalFunction(keyName, keyValue);
    }
    return;
}
localStorage.setItem("test", "blah");

I've done a jsfiddle for you to test it, as in the code snippet, local storage won't work.

I've tried with and without window, it won't work either case.

We can't see it correctly in the jsfiddle but the error is at the line : originalFunction(keyName, keyValue)

I've done the override corresponding to this question. But it doesn't seems to work.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I've found the problem.
Apparently, we need to use .apply to call the original method.

I've updated the fiddle, so it's the working version now. Here's a snippets for coherence :

let originalFunction = window.Storage.prototype.setItem;
window.Storage.prototype.setItem = function(keyName, keyValue) {
    console.log("Override worked ! ")
    let currentState = localStorage.getItem("disableStorage");
    if (currentState === null || keyName === "disableStorage") {
        originalFunction.apply(this, arguments);
    }
    return;
}
localStorage.setItem("test", "blah");

The snippet won't work but the code does.

I've found the synthax here.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda