Uncaught error extension context invalidated

How to avoid "Extension context invalidated" errors when messaging AFTER an Extension update?, google-chrome-extension

When an extension is unloaded, the existing content scripts lose their connection to the rest of the extension—i.e. ports close, and they would be unable to use runtime.sendMessage()—but the content scripts themselves still continue to work, as they’re already injected into their pages.

It’s the same when an extension is reloaded: those existing content scripts will still be there, but unable to send messages; attempts to do so cause errors like the one you’re encountering. Further, as it’s common for extensions to inject their content scripts into existing tabs when they are loaded (on Chrome—Firefox does that automatically), you’ll end up with more than one copy of the content script running in a given tab: the original, now-disconnected one, and the current, connected one.

Problems can arise if either: (1) your original content script is still trying to communicate with the rest of the extension or (2) your original content script does things like modify the DOM, as you could end up with those changes done more than once.

That’s probably why you’re still getting the error even after re-injecting your content scripts: the error is coming from the original content script that’s still there, but disconnected.

This has paraphrased some helpful background information that I found when previously researching this problem. Note that Firefox automatically unloads content scripts (more on that later).

Solutions

If you are not automatically re-injecting your content scripts, then you can try to get the existing script to reconnect on upgrade, as per wOxxOm’s comment above.

Here’s some further info and advice, particularly useful if you inject new content scripts and want to disable the original, disconnected, one when a new one is injected.

Regardless of whether you would like to try to reconnect using the existing content script, or stop the original content script from making further changes and inject a new one, you need to detect that an unload has occurred. You can use the port’s disconnect handler to catch when your extension is unloaded. If your extension only uses simple one-time message passing, and not ports, then that code is as simple as running the following when your content script starts up (I first saw this technique in some code from lydell).

browser.runtime.connect().onDisconnect.addListener(function() {
    // clean up when content script gets disconnected
})

On Firefox, the port’s disconnect is not fired, because the content scripts are removed before they would receive it. This has the advantage that this detection isn’t necessary (nor is manual content script injection, as content scripts are injected automatically too), but it does mean that there’s no opportunity to reset any changes made to the DOM by your content script when it was running.

Содержание

  1. Uncaught Error: Extension context invalidated. #20811
  2. Comments
  3. How to avoid «Extension context invalidated» errors when messaging AFTER an Extension update?
  4. 6 Answers
  5. Solutions
  6. Uncaught error: Extension context invalidated #305
  7. Comments
  8. Как избежать ошибок «Контекст расширения недействителен» при отправке сообщений ПОСЛЕ обновления расширения?
  9. Решения

Uncaught Error: Extension context invalidated. #20811

I am added react developer tool extension in my chrome but it’s continuously throwing an «Uncaught Error: Extension context invalidated» this error, I try this extension in Firefox and it is smoothly running. so what is a problem with chrome.

The text was updated successfully, but these errors were encountered:

Could you show a screenshot of the error or say where it is? Also, try reinstalling it.

This bug report doesn’t have much info.

What Chrome version are you using? Which operating system (and version) are you using?

Sounds like an error that would happen if you updated the DevTools extension and then went back to a page where you had been using it. In that case the fix is just to close and re-open the developer tools pane and reload the page. (Or you could just restart your browser.)

I found this issue playing while doing some babysteps in react and getting the same error in Chrome dev console with the React developer extension enabled.

Info:
Ubuntu 20.04
Chromium
Version 89.0.4389.128 (Official Build) snap (64-bit)

Console:
Uncaught Error: Extension context invalidated.
at injectGlobalHook.js:526
script.src = chrome.runtime.getURL(‘build/react_devtools_backend.js’);

I get it in some code i was refactoring from React class components to react function components

But i cannot specifically locate the code triggering it.

It might be triggered by as simple code as:

function Button() <
return TEST;
>

Источник

How to avoid «Extension context invalidated» errors when messaging AFTER an Extension update?

I am trying to create a smooth experience for users of my Chrome Extension after I release updates.

I reinject my content script on an update of the app, and my functionality works even if the user continues to use my Extension on a page that has NOT been refreshed after the Extension update. Refreshing the page is ideal, but I don’t want to have to force that on my users.

However, I get the following errors in my content script console (the page the content script is inserted into) AFTER the Extension updates but BEFORE the page is refreshed when my code attempts to message from the content script/page to my background page:

Uncaught Error: Extension context invalidated.

Is there a way to ‘rebuild’ the connection? I’ve tried a long-lived port and regular messaging — updating the Extension has the same effect.

Any ideas/direction appreciated.

Here is my simple messaging code (in the content script) that throws the error. but IS able to communicate with the background script:

6 Answers

When an extension is unloaded, the existing content scripts lose their connection to the rest of the extension—i.e. ports close, and they would be unable to use runtime.sendMessage() —but the content scripts themselves still continue to work, as they’re already injected into their pages.

It’s the same when an extension is reloaded: those existing content scripts will still be there, but unable to send messages; attempts to do so cause errors like the one you’re encountering. Further, as it’s common for extensions to inject their content scripts into existing tabs when they are loaded (on Chrome—Firefox does that automatically), you’ll end up with more than one copy of the content script running in a given tab: the original, now-disconnected one, and the current, connected one.

Problems can arise if either: (1) your original content script is still trying to communicate with the rest of the extension or (2) your original content script does things like modify the DOM, as you could end up with those changes done more than once.

That’s probably why you’re still getting the error even after re-injecting your content scripts: the error is coming from the original content script that’s still there, but disconnected.

This has paraphrased some helpful background information that I found when previously researching this problem. Note that Firefox automatically unloads content scripts (more on that later).

Solutions

If you are not automatically re-injecting your content scripts, then you can try to get the existing script to reconnect on upgrade, as per wOxxOm’s comment above.

Here’s some further info and advice, particularly useful if you inject new content scripts and want to disable the original, disconnected, one when a new one is injected.

Regardless of whether you would like to try to reconnect using the existing content script, or stop the original content script from making further changes and inject a new one, you need to detect that an unload has occurred. You can use the port’s disconnect handler to catch when your extension is unloaded. If your extension only uses simple one-time message passing, and not ports, then that code is as simple as running the following when your content script starts up (I first saw this technique in some code from lydell).

On Firefox, the port’s disconnect is not fired, because the content scripts are removed before they would receive it. This has the advantage that this detection isn’t necessary (nor is manual content script injection, as content scripts are injected automatically too), but it does mean that there’s no opportunity to reset any changes made to the DOM by your content script when it was running.

Источник

Uncaught error: Extension context invalidated #305

Similar to #131, maybe?
Was definitely seeing #127.
Not sure if this SO is relevant/helpful?

Note that I uninstalled the extension (kind of coincidentally, but suspecting that it was causing #127) on the same day as the Mar 22 update, so I haven’t had a chance to try the update yet, but I will reinstall and run with it for a few days, and report back. I just wanted to show where the error happens, in case it’s helpful.

The text was updated successfully, but these errors were encountered:

Sorry about this one and thanks for your detailed report. I already found and fixed it in development in #296, though it’s not in a release yet (looks like enough has been changed recently to make a new release, however, so I can do that this evening).

This shouldn’t be causing any performance issues such as #127. My understanding is that the guarding implemented around the mutation observer has been working well. Since then, the scanning code has got faster—though more significantly, and very recently in #269, the number of scans has been reduced even further (though the implementation of #269 caused #296—oops :-)).

I’ll mark this as a dupliate for now, but leave it open until you’re able to test a new release.

If you are finding any performance issues, and are able to share specific URLs, please let me know via a separate issue. I’ve been concentrating recently on providing more info as to what’s going on with changes to dynamic pages, and am hoping that, if there are more things that can be put in place in this area, that will help in finding them.

Источник

Как избежать ошибок «Контекст расширения недействителен» при отправке сообщений ПОСЛЕ обновления расширения?

Я пытаюсь упростить работу пользователей моего расширения Chrome после выпуска обновлений.

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

Однако я получаю следующие ошибки в моей консоли сценария содержимого (страница, в которую вставлен сценарий содержимого) ПОСЛЕ обновления расширения, но ДО обновления страницы, когда мой код пытается передать сообщение из сценария / страницы содержимого на мою фоновую страницу:

Uncaught Error: Extension context invalidated.

Есть ли способ «восстановить» соединение? Я пробовал долгоживущий порт и регулярный обмен сообщениями — обновление расширения дает тот же эффект.

Любые идеи / направления приветствуются.

Вот мой простой код обмена сообщениями (в сценарии содержимого), который выдает ошибку . но МОЖЕТ взаимодействовать с фоновым сценарием:

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

С моим подходом вам не понадобится чрезмерный взлом reconnectToExtension.

Не понимаю. Ваш подход «повторно вставьте сценарии содержимого» имеет хак reconnectToExtension, или у вас есть другой подход?

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

Это работает в Chrome, но у меня не работает в Firefox.

Когда расширение выгружается, существующие сценарии содержимого теряют связь с остальной частью расширения, т. Е. порты закрываются, и они не смогут использовать runtime.sendMessage() , но сами сценарии содержимого продолжают работать, поскольку они уже внедрены на их страницы.

То же самое и при перезагрузке расширения: существующие сценарии содержимого останутся там, но не смогут отправлять сообщения; попытки сделать это вызывают ошибки, подобные той, с которой вы столкнулись. Кроме того, поскольку расширения обычно вставляют свои сценарии содержимого в существующие вкладки при их загрузке (в Chrome — Firefox делает это автоматически), вы получите более одной копии сценария содержимого, запущенного на данной вкладке: исходный, теперь отключенный, и текущий, подключенный.

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

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

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

Решения

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

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

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

В Firefox порт disconnect не запускается, потому что сценарии содержимого удаляются до того, как они его получат. Это имеет то преимущество, что в этом обнаружении нет необходимости (как и ручная инъекция сценария содержимого, поскольку сценарии содержимого также вводятся автоматически), но это означает, что нет возможности сбросить любые изменения, внесенные в DOM сценарием содержимого, когда он Бежал.

Я столкнулся с Chrome Extension message passing: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist . Оказывается, сначала нужно открыть слушатель в фоновом скрипте. Помещение этого в фоновый скрипт решает эту проблему: chrome.runtime.onConnect.addListener(port => < console.log(‘connected ‘, port); if (port.name === ‘hi’) < port.onMessage.addListener(this.processMessage); >>);

. так что очевидно, что вы не сможете редактировать комментарий через пять минут. Что хотел изменить: в фоновом скрипте достаточно chrome.runtime.onConnect.addListener(port => <>); . И ответ отсюда: stackoverflow.com/questions/54181734/…

Можно ли поймать исключение?

Событие onDisconnect (тип: PortDisconnectEvent) запускается также, если нет «обновления» (при первом запуске расширения)

Попробуйте это в своем фоновом сценарии. Многие из старых методов устарели, поэтому я изменил код. Для себя я устанавливаю только один файл content_script. При необходимости вы можете перебрать массив chrome.runtime.getManifest().content_scripts , чтобы получить все файлы .js.

Мне потребовались часы чтения документации, SO, отчетов об ошибках хрома, чтобы, наконец, исправить все ошибки, связанные с этой проблемой «Повторное подключение к среде выполнения после перезагрузки расширения».

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

Вот весь код соответствующие:

manifest.json

Все URL-адреса из content_scripts.matches также должны быть включены в массив permissions . Это необходимо для работы chrome.tabs.executeScript() . Фактически, вы можете отбросить объект content_scripts (поскольку его единственная причина — автоматически вводить сценарии содержимого) и самостоятельно обрабатывать все в background.js (см. документы: «Внедрить скрипты»). Но я сохранил и использовал его для лучшего обзора и из соображений «совместимости».

Обратите внимание, что content_scripts является массивом так же, как и content_scripts[n][‘js’] .

Источник

I am trying to create a smooth experience for users of my Chrome Extension after I release updates.

I reinject my content script on an update of the app, and my functionality works even if the user continues to use my Extension on a page that has NOT been refreshed after the Extension update. Refreshing the page is ideal, but I don’t want to have to force that on my users.

However, I get the following errors in my content script console (the page the content script is inserted into) AFTER the Extension updates but BEFORE the page is refreshed when my code attempts to message from the content script/page to my background page:

Uncaught Error: Extension context invalidated.

Is there a way to ‘rebuild’ the connection? I’ve tried a long-lived port and regular messaging — updating the Extension has the same effect.

Any ideas/direction appreciated.

Here is my simple messaging code (in the content script) that throws the error…but IS able to communicate with the background script:

chrome.runtime.sendMessage({ msg: "recordFeedback", obj: commentObj, source: source}, function(response){
  console.log('Sent to DB...response was: ', response, response.recordFeedbackResponse);
});

When an extension is unloaded, the existing content scripts lose their connection to the rest of the extension—i.e. ports close, and they would be unable to use runtime.sendMessage()—but the content scripts themselves still continue to work, as they’re already injected into their pages.

It’s the same when an extension is reloaded: those existing content scripts will still be there, but unable to send messages; attempts to do so cause errors like the one you’re encountering. Further, as it’s common for extensions to inject their content scripts into existing tabs when they are loaded (on Chrome—Firefox does that automatically), you’ll end up with more than one copy of the content script running in a given tab: the original, now-disconnected one, and the current, connected one.

Problems can arise if either: (1) your original content script is still trying to communicate with the rest of the extension or (2) your original content script does things like modify the DOM, as you could end up with those changes done more than once.

That’s probably why you’re still getting the error even after re-injecting your content scripts: the error is coming from the original content script that’s still there, but disconnected.

This has paraphrased some helpful background information that I found when previously researching this problem. Note that Firefox automatically unloads content scripts (more on that later).

Solutions

If you are not automatically re-injecting your content scripts, then you can try to get the existing script to reconnect on upgrade, as per wOxxOm’s comment above.

Here’s some further info and advice, particularly useful if you inject new content scripts and want to disable the original, disconnected, one when a new one is injected.

Regardless of whether you would like to try to reconnect using the existing content script, or stop the original content script from making further changes and inject a new one, you need to detect that an unload has occurred. You can use the port’s disconnect handler to catch when your extension is unloaded. If your extension only uses simple one-time message passing, and not ports, then that code is as simple as running the following when your content script starts up (I first saw this technique in some code from lydell).

browser.runtime.connect().onDisconnect.addListener(function() {
    // clean up when content script gets disconnected
})

On Firefox, the port’s disconnect is not fired, because the content scripts are removed before they would receive it. This has the advantage that this detection isn’t necessary (nor is manual content script injection, as content scripts are injected automatically too), but it does mean that there’s no opportunity to reset any changes made to the DOM by your content script when it was running.

if(typeof chrome.app.isInstalled!=='undefined'){
   chrome.runtime.sendMessage()
}

Когда расширение выгружается, существующие сценарии содержимого теряют связь с остальной частью расширения, т. Е. порты закрываются, и они не смогут использовать runtime.sendMessage(), но сами сценарии содержимого продолжают работать, поскольку они уже внедрены на их страницы.

То же самое и при перезагрузке расширения: существующие сценарии содержимого останутся там, но не смогут отправлять сообщения; попытки сделать это вызывают ошибки, подобные той, с которой вы столкнулись. Кроме того, поскольку расширения обычно вставляют свои сценарии содержимого в существующие вкладки при их загрузке (в Chrome — Firefox делает это автоматически), вы получите более одной копии сценария содержимого, запущенного на данной вкладке: исходный, теперь отключенный, и текущий, подключенный.

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

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

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

Решения

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

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

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

browser.runtime.connect().onDisconnect.addListener(function() {
    // clean up when content script gets disconnected
})

В Firefox порт disconnect не запускается, потому что сценарии содержимого удаляются до того, как они его получат. Это имеет то преимущество, что в этом обнаружении нет необходимости (как и ручная инъекция сценария содержимого, поскольку сценарии содержимого также вводятся автоматически), но это означает, что нет возможности сбросить любые изменения, внесенные в DOM сценарием содержимого, когда он Бежал.

Понравилась статья? Поделить с друзьями:
  • Uncaught error dropzone already attached
  • Uncaught error class evtimer not found
  • Uncaught error call to undefined function imagecreatefrompng
  • Uncaught error call to undefined function gregwar captcha imagecreatetruecolor
  • Uncaught error call to undefined function curl init