Ошибка unchecked runtime lasterror

This error is not important in this case, but I’ll explain it and how to get rid of it.

What is this error?

Chrome APIs are mostly asynchronous: you have a callback that is called when the operation completes.

In case of chrome.fileSystem.chooseEntry, the chosen entry (or entries) will be passed to a callback:

chrome.fileSystem.chooseEntry(
  {/* options */},
  function(entry) {
    // This is the callback for the API call; you can do something with entry
  }
);

However, the API is not guaranteed to yield a result. For example, as in your case, the user may refuse to provide access by clicking «Cancel». Then there is no entry to work with, and you might want some explanation as to why that happened. How to raise an error without polluting all callbacks with an extra «error» argument?

Usually, Chrome deals with this by setting a global variable, chrome.runtime.lastError, at the time the callback is called. It is uniform across Chrome async APIs to use this instead of an error argument. In fact, quoting the chrome.fileSystem docs:

All failures are notified via chrome.runtime.lastError.

  • If everything is all right, it will be undefined.
  • If there is a problem, it will be non-empty, and chrome.runtime.lastError.message will explain what’s wrong.

However, some callbacks did not check for this error variable. This may indicate a programming error, and Chrome added checks that chrome.runtime.lastError is actually checked (evaluated) in a callback. If not, it considers this to be an unhandled exception, and throws this error.

Why do I say it’s not important?

While it’s an error, it won’t break execution of your program (it’s thrown at the end of an async task), and won’t really be displayed to your users.

And while I say it’s not important, you should check you program’s logic. It may or may not be all right — this is intended to be a (stern) warning.

Why does it exist?

To warn, you, the developer, that your code probably tries to use a result that does not exist, because something went wrong.

It’s possible you’re already checking for an error, e.g.

if (entry) {
  // Process entry
} else {
  // Something went wrong (but what?)
}

Chrome does not employ complex heuristics to see if your code expects this possibility. As noted, errors are reported via chrome.runtime.lastError, and you’re expected to check it.

Note that this error is only raised when something bad does occur, and not when the API call finishes normally.

Can I catch it?

Not really; it’s not raised by your code, but the cleanup code that handles async tasks in Chrome API; therefore using try ... catch in your callback won’t help. Since it’s asynchronous, using try around the original API call won’t help either.

What to do with it?

You should add logic to your callback that checks for problems the way Chrome expects it, and probably react to it.

function(entry) {
  if(chrome.runtime.lastError) {
    // Something went wrong
    console.warn("Whoops.. " + chrome.runtime.lastError.message);
    // Maybe explain that to the user too?
  } else {
    // No errors, you can use entry
  }
}

As long as Chrome sees that you checked the value when there is an error (that is, evaluated it within your callback), the error will not be thrown.

У меня возникает следующая ошибка в консоли Chrome Dev Tools при каждой загрузке страницы моего приложения Node / Express / React:

Unchecked runtime.lastError: не удалось установить соединение. Конец приема не существует

Эта ошибка ссылается на localhost /: 1. При наведении курсора на него отображается http: // localhost: 3000 / — адрес, по которому я просматриваю приложение в браузере.

Кто-нибудь знает, что происходит? Большинство других потоков, которые, как я обнаружил, вызывают эту ошибку, похоже, связаны с кем-то, пытающимся разработать расширение Chrome, и даже в этом случае они, как правило, имеют очень мало ответов.

  • 1 Вы можете увидеть мое решение по заданному вопросу. stackoverflow.com/questions/54181734/…
  • Все ответы на этот вопрос такие: «Это не было вызвано моим кодом. Мне пришлось отключить расширение XY». Если вы ищете решение с точки зрения разработчика, см. Связанные вопросы и ответы выше.

Я получал ту же самую ошибку (за исключением того, что у моего приложения нет серверной части и интерфейса React), и я обнаружил, что она исходила не из моего приложения, а на самом деле из «Контроллера скорости видео» Chrome расширение. Если вы не используете это расширение, попробуйте отключить все свои расширения, а затем снова включить их по одному?

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

  • +1 Верно для меня. Я видел это с каждым встроенным iframe YouTube при включении расширения Youtube Playback Speed ​​Control.

Решение

Для Chrome:

  1. У вас открыто окно с ошибкой консоли, откройте второе новое окно.

  2. Во втором окне перейдите по ссылке: chrome: // extensions

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

  4. Если ошибка исчезла, удалите расширение.

  • 1 Что делать, если мне нужно расширение?

Удаление расширения Chrome «Udacity Frontend Feedback» решило проблему.

  • То же самое здесь, забыл, что это было там.

Если вы разработчик расширения, то увидите, что это сообщение расширения Chrome: Unchecked runtime.lastError: не удалось установить соединение. Конец приема не существует

Суть проблемы в том, что поведение chrome API меняется, и вам нужно добавить обходной путь.

Я обнаружил ту же проблему при разработке расширений Chrome. Я наконец нашел основную проблему.

Unchecked runtime.lastError: не удалось установить соединение. Конец приема не существует

Ключевая проблема заключается в том, что когда отправляет сообщение на активную вкладку через chrome.tabs.sendMessage, на странице не готов или не перезагружается. При отладке. Мы должны убедиться, что content.js активен. И это не может быть страница без обновления, старые страницы не обновляют вас сами js

Вот мой код:


  • В приведенном выше примере sendResponse был вызван синхронно. Если вы хотите использовать sendResponse асинхронно, добавьте return true; обработчику события onMessage. Итак, вы правы.
  • 3 это единственный ответ, который имеет технический смысл для разработчика :(

Для меня это происходило в Chrome, и я обнаружил, что это McAfee WebAdvisor. Как только я отключил его, сообщение исчезло:

Для меня это был разделитель вкладок: https://chrome.google.com/webstore/detail/tab-bundler/ooajenhhhbdbcolenhmmkgmkcocfdahd

Отключение расширения устранило проблему.

  • То же самое для меня, расширение сборщика вкладок … при использовании edge он отображает уникальный идентификатор расширения, и, таким образом, вы можете найти его и отключить вместо того, чтобы идти по одному, как предлагают другие ответы.

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


  • все, спасибо.

Для меня ошибка была связана с расширением onelogin chrome. Его удаление устранило проблему.

Расширение Cacher в моем случае — но да, отключите каждое, а затем перезагрузите страницу

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

Я тестировал свое расширение на странице / вкладке . Тестирование на другой вкладке решило эту проблему. Думаю, такое может случиться и с .

Как ни странно для себя я просто отключил все свои расширения и ошибка исчезла.

Однако после повторного включения всех отключенных мною ошибка все равно исчезла.

Обычно это вызвано расширением.

Если вы не хотите отключать или удалять расширение, которое вызывает эту ошибку, вы можете отфильтровать эту конкретную ошибку, набрав в поле Фильтр в консоли:

Насколько я знаю, этот фильтр будет действовать до тех пор, пока вы не удалите его вручную, вы можете закрыть и снова открыть консоль, перезапустить Chrome и т. Д. Столько, сколько захотите, и фильтр никогда не будет удален автоматически.

  • Хорошо, но что это на самом деле означает?
  • @ Брад Что это значит? Регулярное выражение? Он просто отфильтровывает ошибки с текстом .

Я получаю сообщение только на первой странице Chrome =
Когда Chrome не запущен, я открываю его — либо напрямую, либо дважды щелкнув страницу на рабочем столе.
(Я не знаю, имеет ли это значение, но у меня отключен параметр «Продолжать запуск фоновых приложений при закрытии Google Chrome».)
Итак, я предполагаю, что это попытка шпионажа в Chrome / «улучшения взаимодействия с пользователем».
Я не знаю, что он пытается отправить, но я рад, что он не может! :)
Итак, вторая (или любая, кроме первой) вкладка не содержит ошибок.
== Не нужно ничего отключать (расширения и т. Д.).

Unchecked runtime.lastError: не удалось установить соединение. Приемного конца не существует.

Я «добился» этой ошибки после

  1. установка расширения Debugger for Chrome в Visual Studio Code,
  2. отладка моего кода и
  3. закрытие и повторное открытие окна Chrome без отладки. (Во время отладки я оставил Chrome с запущенным приложением.)

Решения:

  • Прекратите использовать расширение.
  • Обновите окно Chrome без отладки.
  • Используйте другой отладчик.

Конечно, ошибка консоли появляется снова, когда я повторяю шаги 2 и 3, указанные выше, с помощью отладчика для Chrome. Это побуждает меня использовать вместо этого другие отладчики. Тогда я не ошибаюсь, что мой собственный код вызвал ошибки консоли!

2020/02/21

Марат

19

0

info | mistakes |

У нас в консоли появилась ошибка Unchecked runtime.lastError: The message port closed before a response was received. как удалить, как убрать такую ошибку!

Если примерно перевести данную строку на английском, то получим примерно:

Ошибка времени выполнения : порт сообщения был закрыт до получения ответа.

  1. Как исправить ошибку The message port closed before a response was received.
  2. Ищем ошибку Unchecked runtime.lastError: The message port closed before a response was received.
  1. Как исправить ошибку The message port closed before a response was received.

    Открываем настройки расширения в браузере — они могут называться по разному и могут находиться в разных местах! Пример показываю на Яндекс браузере:

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

    Нажмите, чтобы открыть в новом окне.

    Как исправить ошибку  The message port closed before a response was received.

  2. Ищем ошибку Unchecked runtime.lastError: The message port closed before a response was received.

    Теперь нужно воспользоваться самым древним и самым научным способом поиска ошибок он называется

    МЕТОД НАУЧНОГО ТЫКА!!! wall
    смайлы

    Берем по очереди, включаем, выключаем перезагружаем страницу и ждем, какое расширение глючит… и так пока не найдёте кто отвечает за вывод данной ошибки:

    Unchecked runtime.lastError: The message port closed before a response was received.

    Я нашел, кто виновник этой ошибки…

    Нажмите, чтобы открыть в новом окне.

    Ищем ошибку Unchecked runtime.lastError: The message port closed before a response was received.

Не благодарите, но ссылкой можете поделиться!

Теги :

COMMENTS+

 
BBcode


How to fixunchecked runtime lasterror could not establish connectionThe unchecked runtime.lasterror: could not establish connection receiving end does not exist error is fixed by disabling a Chrome extension. The whole process of solving this issue usually consists of several steps, and we are going to explain and exemplify all.

We are also going to answer some of the most common questions users have once been faced with this error on their program. By the time you are done reading this article, you are going to know all the necessary steps you need to take to fix this error.

Contents

  • Why Is the Unchecked runtime.lasterror: Could Not Establish a Connection. Receiving End Does Not Exist Error Happening?
  • How To Fix This Error?
    • – Code Example 1:
    • – Code Example 2
    • – Including the Last Part of the Example Code
    • – Code Example 3
  • Solution 2
    • – Creating the Necessary Code for This Solution
    • – Code Example 4
  • Removing a Common Extension That Causes the Error
    • – Code Example 5
  • FAQ
    • – Specific Extensions Version Not Working?
  • Revising the Details

Why Is the Unchecked runtime.lasterror: Could Not Establish a Connection. Receiving End Does Not Exist Error Happening?

This error usually happens due to a problem with a specific Chrome extension inside your main document. The program cannot establish a connection, and many web developers are usually faced with this error while working on Chrome. Lucky for you, fixing this problem is not a difficult process, and it only consists of a couple of steps.

There are several changes in the code you can do but what it usually takes is a simple extension disabling. To better understand why this problem is happening, we are going to recreate the syntax and show you where exactly Chrome discovers and shows this error. Keep reading the following section of this article where we recreate the error and show you an easy fix.

How To Fix This Error?

One of the first steps you are supposed to take while trying to debug an error is specifying where things go wrong. That is exactly why we are going to show you an example that recreates this problem and shows how Chrome handles it.

In the first step, we are going to show you how does a sending request from the content script looks like:

– Code Example 1:

chrome.runtime.sendMessage({greeting: “hello”}, function (response) {
if (!chrome.runtime.lastError) {
// if you have any response
} else {
// if your document doesn’t have any response, it’s fine but you should actually handle
// it and we are doing this by carefully examining chrome.runtime.lastError
}
});

Now that you better understand the necessary script inside the extension and the way it looks, it is time to create a similar code. Again, this code is going to send the request from the extension to the content script. This time, however, you need to specify the tab where the request is going to be sent.

– Code Example 2

Take a closer look at the following syntax that contains the necessary code:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: “hello”}, function(response) {
if (!chrome.runtime.lastError) {
// if you have any response
} else {
// if your document doesn’t have any response, it’s fine but you should actually handle
// it and we are doing this by carefully examining chrome.runtime.lastError
}
});
});

This syntax wraps the syntax for the sending request. Let us now learn about the receiving end.

– Including the Last Part of the Example Code

The last part of the example code that fixes this error is the most important. It uses an event listener that handles the error message. Again, the complete syntax looks similar either from the extension page or the content script.

– Code Example 3

The complete syntax is shown in the following example and is all the receiving end is supposed to do:

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
“from a content script:” + sender.tab.url :
“from the extension”);
if (request.greeting === “hi”)
sendResponse({farewell: “bye”});
}
);

Web developers include the even listener as the first part of the code and write the rest of the syntax in the following lines. As you could have closely examined all these examples, recreating and solving the error is not a complicated process. However, there is another way you can fix the error that does not establish a connection. We are going to show you how in the following section of this article.

Solution 2

Working with programs and programming languages allows web developers to solve an issue in several ways. We have previously shown you the complete syntax for recreating and fixing this error. However, there is something else you can do to solve this error that appears on your program. It consists of several steps, so take a closer look at the following list to learn more about them:

  1. Open two separate windows on your browser. Keep the error message open inside the first window and use the second window to solve the problem.
  2. Load your active extensions using the second window on your browser.
  3. Make sure to disable and switch off all extensions by toggling the on and off switch. Navigate the first window and refresh the error message included in your program.
  4. Once the error message disappears, make sure to remove the extension from your browser completely.

All the necessary steps you are supposed to take are shown in this list. If you carefully follow each, you are going to fix the error in no time. However, learning from examples is usually better than learning from theory. That is why, in the following section of this guide, we are going to show you the necessary syntax and how web developers can quickly fix this problem.

– Creating the Necessary Code for This Solution

The problem that was thoroughly discussed in this example occurs due to a message sent by the background JavaScript. The active tab is going to receive the message and initiate the content JavaScript on the page, though the document is still not loaded. Therefore, for the process of debugging, you need to make sure that the content JavaScript is still active. In addition, the web page must contain an active refresh cycle because older web pages do not automatically update.

– Code Example 4

The necessary code that offers a solution for this problem is shown in the following example:

//background.js
chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: “hello”}, function(response) {
console.log(response);
});
});
//content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
console.log(request, sender, sendResponse);
sendResponse(‘send this:’+JSON.stringify(“request”));
});

This syntax is going to send the necessary request and allow the browser to fix the issue that the program has. The code contains several functions, values, and event listeners that are going to make everything possible.

However, there is one common extension that usually causes this error, and we are going to show you what it takes to disable it. The following section of this article is going to teach you how to remove the Udacity Frontend Feedback extension from your browser.

Removing a Common Extension That Causes the Error

Specific extensions may sometimes cause unexpected bugs inside your program and the best way to solve the issues is by removing them. For example, many web developers stated that the Udacity Frontend Feedback extension causes unchecked runtime.lasterror: could not establish a connection. receiving end does not exist error message inside their program. Lucky for you, there is an easy way to fix this issue with a simple tweak of the code. First, you have to create a handler for the message callback inside the syntax.

– Code Example 5

This example code is all it takes to fix the issue and remove the message from your program:

window.chrome.runtime.sendMessage(
EXTENSION_ID,
{ message:”—” }, // jsonable message
(result) => {
if (!window.chrome.runtime.lastError) {
// it does not work, that’s it. No more unchecked error
}
}
);
});

As you can see, the error message will no longer be visible on your browser and you can continue working with the rest of the document. Now you know a lot more about the unchecked runtime.lasterror: could not establish a connection. receiving end does not exist error and what is the best way to fix it. All you are supposed to do now is open your browser and try to fix this issue on your own without having any problems.

FAQ

– Specific Extensions Version Not Working?

Certain extensions may sometimes work unproperly or even crash all the time. To fix this issue, you should follow several basic steps. First, take a closer look at the following list to learn more about it:

  1. Open the section More tools > Extensions on your browser.
  2. Turn each extension off by using the toggle button.
  3. Restart the browser and revisit the extensions list.
  4. Turn on each extension, and the problem should be fixed.

This is all it takes to fix this simple problem that may sometimes be quite annoying. If none of this works, repeat the same process, and the problem should be fixed.

Revising the Details

The unchecked runtime.lasterror: could not establish a connection. receiving end does not exist error is fixed by disabling specific Chrome extensions. We have managed to explain the complete process, and you remember the details in the following list:

  • Fixing the unchecked runtime.lasterror: could not establish a connection. receiving end does not exist error does not require any special knowledge
  • You can adjust the code inside the program or disable the specific extension inside your browser
  • If the primary solution does not work, you can repeat the process and fix the issue by using the additional solutions
  • Certain extensions may sometimes fail, but you can easily restart their function by using the toggle button to turn them on and off

Unchecked runtime lasterrorIf you ever thought that fixing this error in your program is complicated, we have shown you that there is not much to it. Furthermore, you will not have any issues debugging the error should you come across it in the future.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

If you are developing a Chrome extension with message passing, then you might have received the following error: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.. There was some type of behavior change that happened post Chrome 72 that affected the way channels are opened. Essentially, if you try to call runetime.connect() before you have a a channel open, then you will get this error (

Stackoverflow
).

So here’s how I setup Message Passing in my Chrome extension to avoid this error.

Manifest.json

I originally had my content script defined in my manifest and used the MATCHES property to have it load on all URLs. However, I learned that if you try to submit a Chrome extension to the webstore that uses a content script that can run on any URL, it will be subject to a longer review time and higher scrutiny and might get rejected. So the simple solution was just to inject my script manually through message passing.

{
    "name": "Simple On Page SEO",
    "version": "1.2",
    "description": "SEO on page analyzer. Look for keyword density, keyword checker in title and meta tags.",
	"manifest_version": 2,
	"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
      "browser_action": {
				"default_popup": "popup.html",
				"default_icon": "icon.png"
		 },
		 "icons": {
		 "128": "icon.png" },
       "permissions": [
				"activeTab",
				"storage"
       ]
    
}

Recall that the popup script is the script that is attached to the popup window on your Chrome extension. I first injected my content script to the page once my extension was loaded.

window.addEventListener('load', (event) => {
  chrome.tabs.executeScript(null, {
    file: 'content.bundle.js', //my content script
  }, () => {
      connect() //this is where I call my function to establish a connection
    });
  });
});

That injects the script then calls my connect function to establish a connection.

function connect() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    const port = chrome.tabs.connect(tabs[0].id);
    port.postMessage({ function: 'html' });
    port.onMessage.addListener((response) => {
      html = response.html;
      title = response.title;
      description = response.description;
    });
  });
}

This creates a connection for message passing and immediately posts a message to that new connection.

Content Script

Remember that the content script runs on the actual webpage that you are on. In this script I listen for a connection and respond to messages:

chrome.runtime.onConnect.addListener((port) => {
  port.onMessage.addListener((msg) => {
    if (msg.function == 'html') {
      port.postMessage({ html: document.documentElement.outerHTML, description: document.querySelector("meta[name='description']").getAttribute('content'), title: document.title });
    }
  });
});

Setting up my Chrome extension like this allowed me to do message passing without receiving the error: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка unox inf
  • Ошибка uncaught typeerror
  • Ошибка unhandled exception in script
  • Ошибка unmountable boot volume на виндовс 10

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии