0

I have to send message from content script to background, a i always got error Uncaught TypeError: Cannot read property 'sendMessage' of undefined

background script is unnecessary, because i have error in the content script

I checked chrome.extension.sendMessage and the same error

content script:

  try {
    chrome.storage.sync.set({
      "channelId": cid
    });
  } catch (error) {
    if (toReload(error.toString())) {

      chrome.runtime.sendMessage({ message: "errorreset" }, function (response) {
          console.log(123);
        });
        
    }
  }

manifest

"background": {
    "page": "notifications.html",
    "persistent": true
  },
  "content_scripts": [
    {
      "matches": ["*://*.youtube.com/*"],
      "js": [
        "lib/jquery-3.6.0.min.js",
        "init.js"
      ],
      "run_at": "document_idle",
      "all_frames": true
    }
  ],
Majster
  • 22
  • 7
  • Please fix your question: it says chrome.extension but the code uses chrome.runtime. Note that there's no chrome.extension.sendMessage in ManifestV3. As for chrome.tabs, content scripts [can't use that](https://developer.chrome.com/extensions/content_scripts). – wOxxOm Jul 17 '21 at 07:38
  • I mean, i checked chrome.extension – Majster Jul 17 '21 at 08:01
  • i have to make script when i got error ` if (toReload(error.toString())) { }` all tabs from "youtube.com" will be refreshed, i try fix error with extension reload and old tabs – Majster Jul 17 '21 at 08:24
  • i have problem with `chrome.storage.sync.set` because after reload the extension i got error `Extension context invalidated` so i could try fix the error and i made ``` if (toReload(error.toString())) { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.reload(tabs[0].id); }); }``` its bad `chrome.tabs.query` but its example. When i got error `Extension context invalidated` so i have to reload all tabs with url (youtube.com) – Majster Jul 17 '21 at 08:40
  • So the problem is caused by reloading the extension. Indeed, doing it invalidates the context of **old** content scripts so they can't use sendMessage. See [this](https://stackoverflow.com/a/57471345) for a solution and [this](https://stackoverflow.com/questions/10994324/chrome-extension-content-script-re-injection-after-upgrade-or-install) as a bonus. – wOxxOm Jul 17 '21 at 08:59
  • ok, never mind i just made simple fix. Code: try { chrome.storage.sync.set({ "channelId": cid }); } catch (error) { if (isReloadExtErr(error.toString())) { window.location.reload(); } } – Majster Jul 17 '21 at 09:33

0 Answers0