Currently facing an issue while attempting to develop a Chrome extension. Occasionally, the chrome.runtime object appears to be incomplete, resulting in missing methods (specifically onMessage, which is essential for my project).
Interestingly, this inconsistency occurs sporadically. I initially thought it might be a timing problem, but I cannot comprehend why establishing a message listener on the background is proving to be challenging.
Provided below is a snippet of my background script:
setTimeout(function () {
console.log("gogo!");
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.type == "tab") {
console.log("tab!");
sendResponse({status: "ok"});
}
}),
2
});
The issue arises when attempting to refer to "chrome.runtime.onMessage" as it returns as undefined.
Appreciate any insights into this matter!
Update: Simplified the prototype but still encountering errors. Below is a breakdown of the project structure:
$tree
.
├── manifest.json
├── src
│ ├── background.html
│ ├── background.js
│ └── test.js
└── vendor
└── jquery.js
2 directories, 5 files
Manifest file (manifest.json):
{
"manifest_version": 2,
"name": "test",
"description": "test",
"version": "1.0",
"author": "test",
"homepage_url": "http://www.test.com",
"content_scripts": [
{
"run_at" : "document_idle",
"matches": ["https://www.google*"],
"js": ["vendor/jquery.js", "src/test.js"]
}
],
"background": {
"page": "src/background.html",
"persistent": false
},
"permissions": [
"tabs",
"https://www.google*"
]
}
Background HTML file (background.html):
<script src="../vendor/jquery.js"></script>
<script src="background.js"></script>
Background JavaScript file (background.js):
function run () {
console.log("gogo!");
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.type == "tab") {
console.log("tab!");
sendResponse({status: "ok"});
}
});
}
run();
Test JavaScript file (test.js):
'use strict';
run();
function run() {
var url = window.location.href;
// Error if no URI
if (!url) {
return 1;
}
var uriRe = /https:\/\/www\.google.*/;
var reParse = uriRe.exec(url);
if (!reParse) {
return 2;
}
chrome.runtime.sendMessage({type: "tab"}, function(response) {
console.log(response);
});
}
Currently using Chrome 49.0.2623.112 (64-bit) on OSX.
Update: Attached a screenshot illustrating the occurrence of failures:
https://i.sstatic.net/CPyBx.png
To emphasize, the issue occurs intermittently (about 50% of the time), suggesting a potential unknown "race" condition complicating the matter.