Не проверено runtime.lastError: Не удалось установить sh соединение. Получающий конец не существует. Chrome Расширение - PullRequest
0 голосов
/ 19 апреля 2020

Я пытаюсь получить некоторую информацию со страницы содержимого на всплывающую страницу с расширением chrome.

Вот мой манифест. json:

{
  "name": " Downloader",
  "description": "history ",
  "version": "1.0",
  "permissions": [
    "activeTab",
    "notifications"
  ],
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {
    "all_frames": false,
    "matches": ["<all_urls>"],
    "exclude_matches": [],
      "js": [
        "/src/jquery.js",
        "/src/sheet-min.js",
        "/src/file-saver-min.js"
      ]

      // "css": [
      //   "js/content/page.css"
      // ]
    }
  ],
  "content_scripts": [{
    "matches": ["*://*.ebay.com/*"],
    "js": ["content.js"],
    "run_at": "document_idle",
    "all_frames": false
  }],
  "browser_action": {
      "default_title": "Download History.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "manifest_version": 2
}

background.js

  chrome.runtime.onMessage.addListener((msg, sender) => {
    // First, validate the message's structure.
    if ((msg.from === 'content') && (msg.subject === 'showPageAction')) {
      // Enable the page-action for the requesting tab.
      chrome.browserAction.show(sender.tab.id);
    }
  });

content.js

// Inform the background page that 
// this tab should have a page-action.
function ping() {
  chrome.runtime.sendMessage('ping', response => {
    if(chrome.runtime.lastError) {
      setTimeout(ping, 1000);
    } else {
      chrome.runtime.sendMessage({
        from: 'content',
        subject: 'showPageAction',
      });
    }
  });
}

ping();


  // Listen for messages from the popup.
  chrome.runtime.onMessage.addListener((msg, sender, response) => {
    // First, validate the message's structure.
    if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
      // Collect the necessary data. 
      // (For your specific requirements `document.querySelectorAll(...)`
      //  should be equivalent to jquery's `$(...)`.)
      var domInfo = {
        total: document.querySelectorAll('*').length,
        inputs: document.querySelectorAll('input').length,
        buttons: document.querySelectorAll('button').length,
      };

      // Directly respond to the sender (popup), 
      // through the specified callback.
      response(domInfo);
    }
  });

popup.js

const setDOMInfo = info => {
    console.log(info)
};


window.addEventListener('DOMContentLoaded', () => {
    // ...query for the active tab...
    chrome.tabs.query({
      active: true,
      currentWindow: true
    }, tabs => {
      // ...and send a request for the DOM info...
      chrome.tabs.sendMessage(
          tabs[0].id,
          {from: 'popup', subject: 'DOMInfo'},
          // ...also specifying a callback to be called 
          //    from the receiving end (content script).
          setDOMInfo);
    });
  });

Я знаю, что эта ошибка возникает, когда скрипт содержимого отправляет сообщение в фоновый скрипт но фоновый скрипт не готов к приему сообщения. После поиска решения для stackoverflow я решил использовать функцию ping, но, как вы можете видеть выше, но она по-прежнему выдает мне то же сообщение об ошибке.

1 Ответ

0 голосов
/ 19 апреля 2020

Нет chrome .browserAction.show, как вы можете видеть в документации , поэтому слушатель в фоновом режиме. js выдает и прерывает выполнение. Цикл обмена сообщениями никогда не завершается, поэтому для отправителя это выглядит как отсутствие какого-либо получателя.

Каждая часть расширения имеет свои собственные devtools .
открытые devtools для фоновый скрипт и вы увидите ошибку.

Здесь не нужен фоновый скрипт.
Нет необходимости в showPageAction сообщении, потому что browser_action включен по умолчанию.

PS весь код можно упростить, переключившись на программирование c внедрение ( пример ), так что вы можете удалить content_scripts, фоновый скрипт и обмен сообщениями.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...