chrome.extension sometimes undefined in background js

核能气质少年 提交于 2020-01-02 19:13:49

问题


[EDIT]

I have reduced my failing code to a much smaller case.

See https://github.com/deg/tmp-chrome-extension-bug

This is a slightly modified copy of https://developer.chrome.com/extensions/getstarted, changed to include a content script and background page.

Even in this simple extension, chrome.runtime.id is sometimes undefined. It looks like a timing problem.

Instructions to reproduce are the repo readme.

[ORIGINAL TEXT]

I have a chrome extension with a background script "background.js"

In this file, at top level, I have chrome.runtime.onMessage.addListener(...);

I test by doing reload on the extension in chrome://extensions. This usually works, but sometimes chrome.runtime.onMessage is undefined.

In debugging, I've found that, whenever this happens, chrome.extension and chrome.runtime.id are also undefined.

I can make the problem "go away" by repeatedly hitting the reload button until it loads correctly.

I first noticed this problem recently, so assumed it was something I had broken. But, after a session of git bisect and hair-pulling, I see that the problem was in even my earliest versions; just occurring much less frequently.

It looks like there is some timing problem at startup -- maybe something is not initialized until after my code has loaded. So, as my code gets longer, I'm seeing the problem more often. (Just a guess)

What is the correct way to do chrome.runtime.onMessage.addListener in the background. Does it need to be wrapped inside an onSomething? Examples I've seen also do it at top-level. Confused!


回答1:


It looks like this problem is caused by a bad interaction with another extension I had loaded on my machine; probably Symantec's "Norton Security Toolbar". More details in the parallel discussion at https://code.google.com/p/chromium/issues/detail?id=565384



来源:https://stackoverflow.com/questions/34045969/chrome-extension-sometimes-undefined-in-background-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!