Content:
When creating or running an extension in a Google Chrome-based browser, you might encounter an error caused by an unchecked runtime.lastError
.
The browser inspector provides little information on the cause of this error, and it can prove to be rather stubborn if you’re not sure where to look.
Fortunately, this has a simple fix, once you understand the cause.
Asynchronous API
Chrome-based browsers provide a number of APIs, which allow developers to interact with the browser and page content. Many of these APIs run asynchronously, returning promises rather than values.
A JavaScript promise is a representation of a future returned value, for a call that’s running asynchronously. They allow execution to continue, rather than waiting for the asynchronous function to return (which would be synchronous behaviour).
Once the asynchronous code returns, the promise is considered to be ‘fulfilled’.
Many Chrome APIs now return promises, particularly since the introduction of Manifest V3.
Handling Responses
For API calls which have been converted to promises, such as chrome.tabs.sendMessage
, you now need to handle the response once the promise is fulfilled. Failure to do so is the cause of the unchecked runtime.lastError
message.
chrome.tabs.sendMessage(tabId, message, function (response) {
...
})
For the code above, the callback function needs to check for runtime.LastError
in the response. You don’t actually have to do anything if you don’t need to handle the error, but you do need to actively check whether it exists.
chrome.tabs.sendMessage(tabId, message, function (response) {
if (chrome.runtime.lastError) {}
})
This also applies to any other unchecked errors you may encounter. Make sure that you’re handling all response values Chrome expects you to check to eliminate these error messages.