Unchecked runtime lasterror the message port closed before a response was received как исправить

Post is rather old and not closely related to Chrome extensions development, but let it be here.

I had same problem when responding on message in callback. The solution is to return true in background message listener.

Here is simple example of background.js. It responses to any message from popup.js.

chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) {
    // setTimeout to simulate any callback (even from storage.sync)
    setTimeout(function() {
        sendResponse({status: true});
    }, 1);
    // return true;  // uncomment this line to fix error
});

Here is popup.js, which sends message on popup. You’ll get exceptions until you un-comment «return true» line in background.js file.

document.addEventListener("DOMContentLoaded", () => {
    chrome.extension.sendMessage({action: "ping"}, function(resp) {
        console.log(JSON.stringify(resp));
    });
});

manifest.json, just in case :) Pay attention on alarm permissions section!

{
  "name": "TestMessages",
  "version": "0.1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "src/popup.html"
  },
  "background": {
    "scripts": ["src/background.js"],
    "persistent": false
  },
  "permissions": [
    "alarms"
  ]
}

Всем привет, на главной странице сайта появилась ошибка, не пойму в чем беда и как разобраться?
Пока на функционал сайта никак не влияет.
О каком порте идет речь?

Uncaught (in promise) Object {message: "The message port closed before a reponse was received."}

015070f257794908997e394ed0c5f867.PNG


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

    более трёх лет назад

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

Ошибка была из за приложения Wappalyzer Chrome, отключил и стало все нормально.

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

Создаю сайты. Открыл проект, работаю и херак ошибка «Unchecked runtime.lastError: The message port closed before a response was received.», перерыл все, благо нашел этот пост и отключил расширение «MeddleMonkey» все вернулось на круги своя. Если возникнут подобные проблемы, то первым делом проверьте расширения и отключите их все.

AdGuard Антибаннер также выдавал такую ошибку. При отключении плагина больше ошибки не возникало.

Тоже столкнулся с данной проблемой. Решил путем отключения всех расширений, что перестало выдавать ошибку, затем поочередно включал каждое расширение и выявил виновника. У меня это был «Защита от веб-угроз 360».

Отключил расширение Tab Scissors и всё нормализовалось.

Столкнулся с такой же ошибкой. Оказывается, когда делаешь обработку сообщений в chrome.runtime.addListener(hendled()), то выход из обработчика нужно прописывать как return true;
И в content_scripts и в background.


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

29 мая 2023, в 15:27

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

29 мая 2023, в 15:00

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

29 мая 2023, в 14:58

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

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

unchecked runtime.lasterror: the message port closed before a response was received error message can occur if there is any failure while communicating information (request and response) from background javascript and client script. You can see this error message in the browser’s console window.

unchecked runtime.lasterror: the message port closed before a response was received

This error is generally caused by the browser extensions. You are using an unsupported extension or your extension may have been corrupted. If you are developing a custom extension then there may be an issue with the extension code.

In this article we will study how to get rid of unchecked runtime.lasterror: the message port closed before a response was received error message. Go through the article thoroughly to understand the causes of this error message and their possible solutions.

Solution:

Following are the two possible solutions to resolve the error message.

1. Remove Extension

You can go to the chrome://extensions/ and disable all extensions. Now check if you are able to use chrome without any error message.

If you don’t get any error message, then there is an issue with one of the extensions. Enable extensions one by one and test them. In this way, you can identify which extension is the culprit and causing the issue and you can remove that extension. Chrome does not report explicitly which extension really causing the issue. So you have to toggle extensions one by one.

Following is the list of extensions that may cause the error message. Check if you have installed any of the below extensions.

  • 1password extension
  • Color Contrast Analyzer
  • Google Publisher Toolbar
  • Kaspersky browser extension
  • Norton Safe web
  • Tampermonkey
  • MeddleMonkey
  • Pinterest extension
  • Stay focused
  • Piggy – Automatic Coupons & Cash Back
  • BuiltWith Technology Profiler
  • HonorLock
  • Video Downloader Professional

The above list is just an example. It’s not necessary that you are also getting error messages because of the above extensions. We have given the list based on our experience and the feedback we received from our users.

Note:

A. You can use “Disable Extensions Temporarily” extensions to disable and enable all the extension with one click.

B. You can also try using chrome in incognito mode with do not allow extension setting and see if you are able to solve the issue.

If you are still getting the error message then it means there is no issue with the extension. Something else is causing the issue.

Check Other Articles

gotoxy() function in c++

Only integer scalar arrays can be converted to a scalar index

2. Add a return statement in the background message listener

If you are a developer and using or developing any new custom chrome extension then there may be some issue with your extension code that causes the unchecked runtime.lasterror: the message port closed before a response was received error message. Here we have explained in detail what part of the code can cause this error message and how to resolve it.

Please check the onMessage listener code snippet in your extension code. If this listener does not return the response correctly then it can result in the above error message.

Add return true in the onMessage call listener to resolve the error as shown below:

chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) 
{
     setTimeout(function() {
        sendResponse({status: true});
    }, 1);
     return true;  // Add return true to fix the error.
});

Note:

A. For some users breakpoint in the extension code was causing the issue. They were able to get rid of error message by removing the breakpoints. So try removing the breakpoints from the code and see whether error message is disappeared.

B. Sometimes antivirus blocks the custom code execution properly that may result in the error message. So try disabling antivirus extension and see whether it solves the error.

Conclusion:

We hope that the methods mentioned above are useful and you are able to identify the extension that causing the issue or able to fix the custom extension code. If you are still getting the unchecked runtime.lasterror: the message port closed before a response was received error message then please do mention it in the comment section or you can communicate with us using our official mail id hello.technolads@gmail.com

Thank you.

Google Chrome Help

Sign in

Google Help

  • Help Center
  • Community
  • Google Chrome
  • Privacy Policy
  • Terms of Service
  • Submit feedback

Send feedback on…

This help content & information

General Help Center experience

  • Help Center
  • Community

Google Chrome

2020/02/21

Марат

3

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


Понравилась статья? Поделить с друзьями:
  • Найти как человек появился на земле
  • Как составить заявку на котировку
  • Как найти абсолютный прирост базисным методом
  • Как найти периметр прямоугольника по петерсону
  • Как найти тренера для собаки