Ошибка the operation is insecure

Доброго времени суток, гости блога и постоянные читатели. В данной статье я предлагаю вам разобраться с такой ошибкой, как javascript error the operation is insecure. Я постарался собрать здесь как можно больше советов и способов решения данной проблемы.

Поэтому я расскажу вам из-за чего может возникнуть данная ошибка и перечислю несколько эффективных способов ее решения. Ну что ж, приступим!

Где чаще всего появляется данная ошибка и как она переводится?

Для начала вам стоит узнать перевод сообщения «the operation is insecure». Оно переводится как: «Операция небезопасна».

Ознакомившись с данной проблемой и проанализировав жалобы пользователей интернета, я вычислил, что наиболее часто такой error возникает в популярной социальной сети под названием «ВКонтакте». И при чем наиболее часто жалуются те юзеры, которые пользуются браузером Mozilla Firefox.

Как выяснилось, эта проблема в основном возникает только в названном браузере, при этом в одно и то же время ВК отлично работает в других обозревателях.

Данная ошибка наиболее часть появляется при переходе на вкладку аудиозаписей, сообщений и списка друзей.

Именно поэтому далее я перечислю все известные способы устранения описанного error-а, которые подскажут, что делать в аналогичной ситуации и как все исправить.

Воспользуйтесь другим браузером

Конечно некоторые могут зафукать данное предложение. Но оно является наиболее простым и быстрым. Ведь данная проблема зафиксирована только в Firefox и не возникает в других интернет-обозревателях. Советую вам установить Google Chrome, так как он мощнее и быстрее остальных.

Обновите браузер

Обновляем Firefox

Если вы не можете расстаться с Mozilla Firefox, то попробуйте данное решение.

Если вы давно не обновляли версию данного интернет-обозревателя и она у вас не обновляется автоматически, то неудивительно, что вы встретились с такой ошибкой.

Чтобы воспользоваться данным способом, вам следует:

  • кликнуть по кнопке «Меню» и зайти в «Справку», а точнее в раздел «О Firefox»;Меню браузера Firefox
  • Перед вами отобразится окно с информацией и запустится проверка на наличие новых версий;
  • Когда все будут готово к установке апдейтов, вы увидите кнопку «Перезапустить Firefox для обновления». Нажмите на нее.

После проверьте ВК. Если ошибка все равно возникает, то переходите к следующим вариантам борьбы.

Произведите полную очистку кэша

Возможно при работе в интернете в кэше и/или других временных файлах засело что-то эдакое. Для очистки браузера нажмите сочетание клавиш ctrl+Shift+Delete. Перед вами появиться окно, в котором можно настроить параметры удаления истории.

Очистка все истории

Обязательно удаляйте историю за все время, а также поставьте галочку напротив кэша и можно даже напротив куки (однако в этом случае из базы удалятся все ваши сохраненные логины и пароли, и вам придется авторизироваться повторно).

После проделанных операций обновите веб-страницу (можете нажать на знак обновления страницы или нажать F5) и проверьте работу социальной сети.

Отключите все дополнения и расширения

Возможно проблема возникла из-за подключения дополнений, которые были или непроверенными до конца, или небезопасными. В этом случае вам стоит сначала обратить внимание на все плагины, загрузчики и другие дополнения, которые напрямую относятся к работе соцсети VK.

Для начала удалите ненужные приложения. После обновите браузер описанным выше способом и проверьте работу приложения. Если проблема была скрыта в дополнениях, то соцсеть после выполненных действий начнет работать корректно.

Если же дополнительные программы вам необходимы, и вы не решаетесь их удалять, то просто обновите последние и проверьте работу социальной сети. Возможно с подключением новых версий плагинов или расширений данная проблема устранится сама собой. Однако если обновление не помогло, то возможно дополнение и есть источником вызова ошибки.

Вот я и перечислил вам основные методы борьбы с возникающей ошибкой «the operation is insecure». Надеюсь, они помогли справиться с возникшим error-ом.

Подписывайтесь на обновления моего обучающего блога и не забывайте делиться понравившимися статьями с друзьями и знакомыми. До скорой встречи! Пока-пока!

С уважением, Роман Чуешов

I am using Backbone.LocalStorage plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox.

DOMException [SecurityError: «The operation is insecure.»
code: 18
nsresult: 0x80530012
location: http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]

I am using python simpleHttpServer

How can I resolve this error?

UPDATE

Here is my code.

paths: {
    'jquery'        : 'libs/jquery/dist/jquery',
    'underscore'    : 'libs/underscore/underscore',
    'backbone'      : 'libs/backbone/backbone',
    'localStorage'  : 'libs/backbone.localStorage/backbone.localStorage',
    'text'          : 'plugins/text'
}

Here is collection where localStorage is used.

var Items = Backbone.Collection.extend({

    model: SomeModel,

    localStorage: new Backbone.LocalStorage('items'),
});

UPDATE 2

I am using firefox 36.

UPDATE 3

It seems like it is a CORS issue but my firefox version is 36. Which should be fine.

UPDATE 4

I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.

I am using Backbone.LocalStorage plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox.

DOMException [SecurityError: «The operation is insecure.»
code: 18
nsresult: 0x80530012
location: http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]

I am using python simpleHttpServer

How can I resolve this error?

UPDATE

Here is my code.

paths: {
    'jquery'        : 'libs/jquery/dist/jquery',
    'underscore'    : 'libs/underscore/underscore',
    'backbone'      : 'libs/backbone/backbone',
    'localStorage'  : 'libs/backbone.localStorage/backbone.localStorage',
    'text'          : 'plugins/text'
}

Here is collection where localStorage is used.

var Items = Backbone.Collection.extend({

    model: SomeModel,

    localStorage: new Backbone.LocalStorage('items'),
});

UPDATE 2

I am using firefox 36.

UPDATE 3

It seems like it is a CORS issue but my firefox version is 36. Which should be fine.

UPDATE 4

I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.

Доброго времени суток, гости блога и постоянные читатели. В данной статье я предлагаю вам разобраться с такой ошибкой, как javascript error the operation is insecure. Я постарался собрать здесь как можно больше советов и способов решения данной проблемы.

Поэтому я расскажу вам из-за чего может возникнуть данная ошибка и перечислю несколько эффективных способов ее решения. Ну что ж, приступим!

Где чаще всего появляется данная ошибка и как она переводится?

Для начала вам стоит узнать перевод сообщения «the operation is insecure». Оно переводится как: «Операция небезопасна».

Ознакомившись с данной проблемой и проанализировав жалобы пользователей интернета, я вычислил, что наиболее часто такой error возникает в популярной социальной сети под названием «ВКонтакте». И при чем наиболее часто жалуются те юзеры, которые пользуются браузером Mozilla Firefox.

Как выяснилось, эта проблема в основном возникает только в названном браузере, при этом в одно и то же время ВК отлично работает в других обозревателях.

Данная ошибка наиболее часть появляется при переходе на вкладку аудиозаписей, сообщений и списка друзей.

Именно поэтому далее я перечислю все известные способы устранения описанного error-а, которые подскажут, что делать в аналогичной ситуации и как все исправить.

Воспользуйтесь другим браузером

Конечно некоторые могут зафукать данное предложение. Но оно является наиболее простым и быстрым. Ведь данная проблема зафиксирована только в Firefox и не возникает в других интернет-обозревателях. Советую вам установить Google Chrome, так как он мощнее и быстрее остальных.

Обновите браузер

Обновляем Firefox

Если вы не можете расстаться с Mozilla Firefox, то попробуйте данное решение.

Если вы давно не обновляли версию данного интернет-обозревателя и она у вас не обновляется автоматически, то неудивительно, что вы встретились с такой ошибкой.

Чтобы воспользоваться данным способом, вам следует:

  • кликнуть по кнопке «Меню» и зайти в «Справку», а точнее в раздел «О Firefox»;Меню браузера Firefox
  • Перед вами отобразится окно с информацией и запустится проверка на наличие новых версий;
  • Когда все будут готово к установке апдейтов, вы увидите кнопку «Перезапустить Firefox для обновления». Нажмите на нее.

После проверьте ВК. Если ошибка все равно возникает, то переходите к следующим вариантам борьбы.

Произведите полную очистку кэша

Возможно при работе в интернете в кэше и/или других временных файлах засело что-то эдакое. Для очистки браузера нажмите сочетание клавиш ctrl+Shift+Delete. Перед вами появиться окно, в котором можно настроить параметры удаления истории.

Очистка все истории

Обязательно удаляйте историю за все время, а также поставьте галочку напротив кэша и можно даже напротив куки (однако в этом случае из базы удалятся все ваши сохраненные логины и пароли, и вам придется авторизироваться повторно).

После проделанных операций обновите веб-страницу (можете нажать на знак обновления страницы или нажать F5) и проверьте работу социальной сети.

Отключите все дополнения и расширения

Возможно проблема возникла из-за подключения дополнений, которые были или непроверенными до конца, или небезопасными. В этом случае вам стоит сначала обратить внимание на все плагины, загрузчики и другие дополнения, которые напрямую относятся к работе соцсети VK.

Для начала удалите ненужные приложения. После обновите браузер описанным выше способом и проверьте работу приложения. Если проблема была скрыта в дополнениях, то соцсеть после выполненных действий начнет работать корректно.

Если же дополнительные программы вам необходимы, и вы не решаетесь их удалять, то просто обновите последние и проверьте работу социальной сети. Возможно с подключением новых версий плагинов или расширений данная проблема устранится сама собой. Однако если обновление не помогло, то возможно дополнение и есть источником вызова ошибки.

Вот я и перечислил вам основные методы борьбы с возникающей ошибкой «the operation is insecure». Надеюсь, они помогли справиться с возникшим error-ом.

Подписывайтесь на обновления моего обучающего блога и не забывайте делиться понравившимися статьями с друзьями и знакомыми. До скорой встречи! Пока-пока!

С уважением, Роман Чуешов

The «SecurityError: The operation is insecure» error occurs when using the window.history.pushState() method in JavaScript. This is a security restriction imposed by web browsers to prevent web pages from manipulating the user’s navigation history. When the error is thrown, it means that the pushState() method can only be used in a secure context, such as a web page loaded using HTTPS. In this scenario, it’s not possible to modify the URL of an HTTP page.

Method 1: Use HTTPS

To fix the SecurityError: The operation is insecure — window.history.pushState() error in JavaScript, you can use HTTPS to encrypt the data being transmitted. This can be done by setting up an SSL certificate on your server and configuring your web application to use HTTPS.

Here’s an example of how to use HTTPS with Node.js:

const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('path/to/key.pem'),
  cert: fs.readFileSync('path/to/cert.pem')
};

const server = https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello, world!');
});

server.listen(443);

In this example, we’re creating an HTTPS server using the https module in Node.js. We’re passing in an options object that includes the path to our SSL key and certificate files. We then create a server and listen on port 443, which is the default port for HTTPS traffic.

Here’s an example of how to use HTTPS with Express.js:

const express = require('express');
const https = require('https');
const fs = require('fs');

const app = express();

const options = {
  key: fs.readFileSync('path/to/key.pem'),
  cert: fs.readFileSync('path/to/cert.pem')
};

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

https.createServer(options, app).listen(443);

In this example, we’re creating an Express.js application and defining a route for the root URL. We’re then creating an HTTPS server using the https module and passing in our options object and the Express.js application. We then listen on port 443 for HTTPS traffic.

Finally, here’s an example of how to redirect HTTP traffic to HTTPS using Apache:

<VirtualHost *:80>
  ServerName example.com
  Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
  ServerName example.com
  SSLEngine on
  SSLCertificateFile /path/to/cert.pem
  SSLCertificateKeyFile /path/to/key.pem
  DocumentRoot /path/to/website
</VirtualHost>

In this example, we’re defining two virtual hosts for our website: one for HTTP traffic on port 80 and one for HTTPS traffic on port 443. The HTTP virtual host redirects all traffic to the HTTPS virtual host using the Redirect directive. The HTTPS virtual host enables SSL encryption using the SSLEngine directive and specifies the path to our SSL certificate and key files using the SSLCertificateFile and SSLCertificateKeyFile directives. We also specify the document root for our website using the DocumentRoot directive.

By using HTTPS to encrypt your data, you can avoid the SecurityError: The operation is insecure — window.history.pushState() error in JavaScript.

Method 2: Use Hash-based Navigation

If you are facing the SecurityError while using window.history.pushState() method in your JavaScript code, one possible solution is to use Hash-based Navigation.

Step 1: Listen to the hashchange event

First, we need to listen to the hashchange event to detect any changes in the URL hash. We can do this by adding an event listener to the window object.

window.addEventListener('hashchange', function() {
  // handle hash change
});

Step 2: Update the URL hash

Next, we need to update the URL hash whenever the user navigates to a new page or performs any action that changes the state of the page. We can do this by setting the location.hash property.

// navigate to page 1
location.hash = '#page1';

// navigate to page 2
location.hash = '#page2';

Step 3: Handle the hash change

Finally, we need to handle the hash change event and update the page content accordingly. We can do this by checking the current value of the location.hash property and updating the page content based on its value.

window.addEventListener('hashchange', function() {
  var hash = location.hash;
  if (hash === '#page1') {
    // update page content for page 1
  } else if (hash === '#page2') {
    // update page content for page 2
  }
});

By using Hash-based Navigation, we can avoid the SecurityError while still providing a smooth user experience. However, keep in mind that this approach has some limitations, such as the inability to use the browser’s back and forward buttons.

Method 3: Use a Polyfill for pushState()

One way to fix the SecurityError with window.history.pushState() is to use a polyfill. A polyfill is a piece of code that provides modern functionality on older browsers that do not support it natively. In this case, we can use the History.js polyfill to add support for pushState().

Here are the steps to use the History.js polyfill:

  1. Download the History.js polyfill from https://github.com/browserstate/history.js/
  2. Include the polyfill in your HTML file:
<script src="path/to/history.js"></script>
  1. Replace your calls to window.history.pushState() with History.pushState():
History.pushState({state:1}, "Title 1", "?state=1");
  1. To handle state changes, use the History.js API:
History.Adapter.bind(window,'statechange',function(){
    var state = History.getState();
    console.log(state.data, state.title, state.url);
});

That’s it! By using the History.js polyfill, you can add support for pushState() on older browsers and avoid the SecurityError.

zkrvndm

@zkrvndm

Софт для автоматизации

При попытке перезаписать содержимое страницы получаю ошибку, что это небезопасно:
SecurityError: The operation is insecure.
Код запускаю из контент-скрипта своего собственного браузерного расширения.

Подскажите, пожалуйста, как я могу использовать document.write в браузере Firefox? Может быть в конфигах браузера есть какая-нибудь хитрая настройка отключающая запрет? Или какое-нибудь особое разрешение для манифеста расширения?


  • Вопрос задан

    более года назад

  • 146 просмотров

Спасибо Aetae за подсказанное решение, которое работает в Firefox:

document.wrappedJSObject.write(''); document.close();

Если запустить метод из контент-скрипта в своем расширении еще до начала отрисовки DOM, то это позволяет предотвратить запуск скриптов сайта, а далее на страницу уже можно спокойно залить свое содержимое.

Пригласить эксперта


  • Показать ещё
    Загружается…

13 июн. 2023, в 17:47

10000 руб./за проект

13 июн. 2023, в 17:38

50000 руб./за проект

13 июн. 2023, в 17:25

5000 руб./за проект

Минуточку внимания

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Open

kilburn opened this issue

Jul 25, 2019

· 40 comments

Labels

help wanted

Issue with a clear description that the community can help with.

status: confirmed

Issue with steps to reproduce the bug that’s been verified by at least one reviewer.

type: bug

An issue or pull request relating to a bug in Gatsby

Comments

@kilburn

Description

With gatsby develop and Firefox Developer Edition (latest version, 69.07b), firefox throws a security error exception when app.js checks if (serviceWorker in navigator), and hence the app cannot be used:

SecurityError

Steps to reproduce

  1. Install firefox developer edition
  2. Run gatsby develop on any gatsby project (no offline plugin nor anything sw-related)

Expected result

You see the website and can develop it normally.

Actual result

You get the error above and hence cannot do anything (the error triggers the react overlay error and does not let you interact with the site at all)

Environment

  System:
    OS: Linux 5.0 Ubuntu 19.04 (Disco Dingo)
    CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
    Shell: 5.0.3 - /bin/bash
  Binaries:
    Node: 10.16.0 - /tmp/yarn--1564036896798-0.009151794373142508/node
    Yarn: 1.17.3 - /tmp/yarn--1564036896798-0.009151794373142508/yarn
    npm: 6.9.0 - /usr/bin/npm
  Languages:
    Python: 2.7.16 - /usr/bin/python
  Browsers:
    Firefox: 68.0
  npmPackages:
    gatsby: ^2.1.27 => 2.13.32
    gatsby-image: ^2.0.31 => 2.2.6
    gatsby-plugin-create-client-paths: ^2.0.4 => 2.1.3
    gatsby-plugin-env-variables: ^1.0.1 => 1.0.1
    gatsby-plugin-manifest: ^2.0.22 => 2.2.3
    gatsby-plugin-react-helmet: ^3.0.8 => 3.1.2
    gatsby-plugin-react-svg: ^2.1.1 => 2.1.1
    gatsby-plugin-remote-images: ^1.0.1 => 1.0.3
    gatsby-plugin-sass: ^2.0.11 => 2.1.3
    gatsby-plugin-sharp: ^2.0.25 => 2.2.8
    gatsby-plugin-typescript: ^2.1.0 => 2.1.2
    gatsby-source-filesystem: ^2.0.23 => 2.1.5
    gatsby-source-s3-image: ^1.5.8 => 1.6.5
    gatsby-transformer-sharp: ^2.1.15 => 2.2.4
moustaxx, saltdotac, skdigital, wamberg, zzzbra, ronaldsmartin, ganevdev, FedericoBiccheddu, wellington1993, bencmbrook, and 16 more reacted with thumbs up emoji

@gatsbot
gatsbot
bot

added
the

stale?

Issue that may be closed soon due to the original author not responding any more.

label

Aug 15, 2019

@gatsbot

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 30 days of inactivity. It’s been at least 20 days since the last update here.

If we missed this issue or if you want to keep it open, please reply here. You can also add the label «not stale» to keep this issue open!

As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contributefor more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 💪💜

@skdigital

I have the same error using firefox developer edition and a new install of gatsby project (exactly the same error).

@gatsbot

Hey again!

It’s been 30 days since anything happened on this issue, so our friendly neighborhood robot (that’s me!) is going to close it.

Please keep in mind that I’m only a robot, so if I’ve closed this issue in error, I’m HUMAN_EMOTION_SORRY. Please feel free to reopen this issue or create a new one if you need anything else.

As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks again for being part of the Gatsby community!

@andresmrm

The problem persists here. Using Firefox Nightly (70.0a1).

@sheedy

Not just nightly, I’m running FF 69.0.

Just ran gatsby new hello-world https://github.com/gatsbyjs/gatsby-starter-hello-world and then gatsby develop and see the same screen as above.

I have FF’s security and privacy settings all turned on but wouldn’t expect that to effect this. Switched them all back to standard and still get this screen.

image

@edowado

Same on firefox 69.0 (64-bit) for linux

@studiospring

Happening on MacOS FireFox 69.0, with FF extensions disabled, vanilla gatsby-starter-default.

gatsby: ^2.15.13 => 2.15.13
gatsby-cli: ^2.7.47 => 2.7.47
gatsby-image: ^2.2.18 => 2.2.18
gatsby-plugin-manifest: ^2.2.16 => 2.2.16
gatsby-plugin-offline: ^2.2.10 => 2.2.10
gatsby-plugin-react-helmet: ^3.1.7 => 3.1.7
gatsby-plugin-sharp: ^2.2.21 => 2.2.21
gatsby-source-filesystem: ^2.1.22 => 2.1.22
gatsby-transformer-sharp: ^2.2.14 => 2.2.14
npmGlobalPackages:
    gatsby-cli: 2.7.44

@zzzbra

I am also seeing this. One (very) slight difference between my case and OPs is the subsequent line is highlighted as the error in my case:

Screen Shot 2019-09-15 at 15 51 08

Also I am running FF Developer Edition 70.0b2

@yansusanto

Also I am running FF Developer Edition 70.0b2

Looks like everyone is facing the same issue and none has a solution.

@kilburn

I worked around the issue by disabling the «Delete cookies and site data when Firefox Developer Edition is closed» option:
imatge

alexvickers, mediasittich, Maria218, adamdva, twei55, stefandevai, davidruvolo51, wildsrincon, iracanyes, aschmois, and 14 more reacted with thumbs up emoji
ronaldsmartin, vgorloff, zzzbra, GenesisVargasJ, britotiagos, ickas, Maria218, stevenson3, daviddortiz, dmithamo, and 6 more reacted with hooray emoji
luenmuvel, ErikAGriffin, and Jedyle reacted with heart emoji
iracanyes, dmithamo, luenmuvel, ErikAGriffin, and rui-shi-0413 reacted with rocket emoji

@yansusanto

Thanks, @kilburn. That did hide the warning.

@Ovicakov

Thank you ! It works on FF Developer edition

@zzzbra

@FedericoBiccheddu

As a temporary workaround, the Incognito mode works fine.

Personally, I don’t want that functionality completely disabled.

Hope it helps 😄

@wardpeet
wardpeet

added
the

help wanted

Issue with a clear description that the community can help with.

label

Nov 15, 2019

@wardpeet

Reading up on some other issues around this, like angular. It looks like we might just need a try catch around the getRegistrations function

@Maria218

I worked around the issue by disabling the «Delete cookies and site data when Firefox Developer Edition is closed» option:
imatge

Thank you so much! This worked for the exact error I was having with my React app. But what exactly is the problem? And why does this work? Should the unregister function in my React app be changed to account for this in some way?

@kilburn

Thank you so much! This worked for the exact error I was having with my React app. But what exactly is the problem? And why does this work? Should the unregister function in my React app be changed to account for this in some way?

The issue is that firefox doesn’t allow any kind of access to navigator.serviceWorker when the «delete cookies and site data when Firefox is closed» option is enabled. I don’t know what reasons did they have for it, but dealing with that issue would just be a matter of surrounding the navigator.serviceWorker access with a try ... catch that captures the SecurityError exception and proceeds as if the browser did not have any serviceWorker functionality.

Maria218, CharlyMartin, i7N3, sharnik, j127, cameronSlupeiks, dmithamo, jmmendivil, Mudo121Bbc, tharders, and RobJacobson reacted with thumbs up emoji

@Maria218

Thank you so much! This worked for the exact error I was having with my React app. But what exactly is the problem? And why does this work? Should the unregister function in my React app be changed to account for this in some way?

The issue is that firefox doesn’t allow any kind of access to navigator.serviceWorker when the «delete cookies and site data when Firefox is closed» option is enabled. I don’t know what reasons did they have for it, but dealing with that issue would just be a matter of surrounding the navigator.serviceWorker access with a try ... catch that captures the SecurityError exception and proceeds as if the browser did not have any serviceWorker functionality.

Oh okay, thanks for the info. I’ll do that

@davidanitoiu

I’m not sure on the side-effects on this one, but so far I add an empty catch to the navigator.serviceWorker.getRegistrations().then(...) every time I run gatsby develop

Takes care of the annoying error for me.

 if (`serviceWorker` in navigator) {
    navigator.serviceWorker.getRegistrations().then(registrations => {
      if (registrations.length > 0)
        console.warn(
          `Warning: found one or more service workers present.`,
          `If your site isn't behaving as expected, you might want to remove these.`,
          registrations
        )
    }).catch(error => {})

@areinmeyer

Just came across this error as well in Firefox 72.

A different option than unchecking the Delete cookies and site data when Firefox is closed is to leave it checked but then go into Manage Permissions option next to the checkmark and add localhost:8000 to the Allow list. Just adding localhost did not work for me, I had to specifically add the port as well.

BoaPi, dijonmusters, jwoptio, marvinbernd, jeesunikim, twei55, jpmarra, clovis-rosa, MSaifAsif, salomon-escobar, and 6 more reacted with thumbs up emoji
jpmarra, MSaifAsif, salomon-escobar, dmithamo, luenmuvel, and magoni reacted with hooray emoji
luenmuvel and farhour reacted with heart emoji
dmithamo, luenmuvel, and alekshs reacted with rocket emoji

@j127

I see the same error in regular Firefox 74 on Ubuntu 16.04 (not Developer Edition). Changing that setting fixes the problem, but then my browser doesn’t have the correct settings any more.

@ArnoSoontjens

Experiencing this too! FF 75.0 (64bit), on Ubuntu 18.04. My ‘workaround’ is to just comment out the entire if-statement’s body, but I have to do that everytime the development server restarts., which is not very convenient.

 if (`serviceWorker` in navigator) {
   /* navigator.serviceWorker.getRegistrations().then(registrations => {
      if (registrations.length > 0)
        console.warn(
          `Warning: found one or more service workers present.`,
          `If your site isn't behaving as expected, you might want to remove these.`,
          registrations
        )
    })*/
  }

@phamvanhiepvn

Thêm try catch hoặc .catch nhé các sếp :)

@j127

Is anyone still seeing this error? I went to see if I could fix it here, but I can’t reproduce it on my computer any more.

@clovis-rosa

Is anyone still seeing this error? I went to see if I could fix it here, but I can’t reproduce it on my computer any more.

Hey @j127 , yes! The error still. I just started a new Gatsby v2.21.37 project and opened it in a Firefox Developer v77.0b9 (64-bit). As a temporary fix I whitelisted the localhost:8000 as described above.

@j127

This seems to work, but I’ll need to read a little more about the contributing guidelines before I make a pull request.

  if (`serviceWorker` in navigator) {
    navigator.serviceWorker
      .getRegistrations()
      .then(registrations => {
        if (registrations.length > 0)
          console.warn(
            `Warning: found one or more service workers present.`,
            `If your site isn't behaving as expected, you might want to remove these.`,
            registrations
          )
      })
      .catch(err => {
        if (/Firefox/.test(navigator.userAgent)) {
          console.error(
            `To reduce storage access error messages during development`,
            `in Firefox, uncheck the setting "Delete cookies and site data when Firefox`,
            `is closed" in your preferences.`
          )
        }
        console.error(err)
      })
  }

It keeps the page from breaking, and it shows a console message in Firefox about how to remove the extra error messages. Let me know if you think there is a better way to handle it.

error

@bradobro

I submitted a minimal fix in #25981. I like @j127 ‘s specific Firefox warning, but opted to omit it, thinking

  • I don’t think we want to advise (possibly inexperienced) developers to turn off browser security.
  • More browsers may add default security settings that cause this fault, and a more generic remedy will cut down on maintenance PR’s.

I’m glad to retract the PR if we think there’s a better way, but wanted to get some active code in place that catches the exception and gives us a foundation for discussion.

@dmithamo

Just came across this error as well in Firefox 72.

A different option than unchecking the Delete cookies and site data when Firefox is closed is to leave it checked but then go into Manage Permissions option next to the checkmark and add localhost:8000 to the Allow list. Just adding localhost did not work for me, I had to specifically add the port as well.

Thanks!
Oh and btw, Manage Permissions is Manage Exceptions on FDE 82 now.
image

@jonathanlinat

Just came across this error as well in Firefox 72.

A different option than unchecking the Delete cookies and site data when Firefox is closed is to leave it checked but then go into Manage Permissions option next to the checkmark and add localhost:8000 to the Allow list. Just adding localhost did not work for me, I had to specifically add the port as well.

It works as described. 👍

image

@Isaac-Tait

This issue popped up for me. Switching to a private window allowed me to load the localhost… I also tried to turn off the «Delete cookies and site data when Firefox Developer Edition is closed» that I saw mentioned as a solution… That did not work.

@RobJacobson

I’m brand-new to Gatsby (but familiar with React). This bug popped up for me tonight with FF 91.0.1 while walking through the official tutorial.

I worked around this using @kilburn’s solution. However, it would be great to get this patched!

@4www
4www

mentioned this issue

Dec 1, 2021

13 tasks

Labels

help wanted

Issue with a clear description that the community can help with.

status: confirmed

Issue with steps to reproduce the bug that’s been verified by at least one reviewer.

type: bug

An issue or pull request relating to a bug in Gatsby

Projects


No open projects

Источник

Понравилась статья? Поделить с друзьями:
  • Ошибка the operation has timed out
  • Ошибка the operation couldn t be completed
  • Ошибка the nvi2 dll file can not be found
  • Ошибка the network adapter could not establish the connection
  • Ошибка the multi part identifier could not be bound