slhck slhck - 2 months ago 22
Javascript Question

How do I catch errors in a JavaScript programmatically injected from a Chrome Extension?

I am using the content script of a Chrome extension to programmatically inject another content script that can access the web page variables and DOM. I do this on YouTube to wait for the


So, I have the file
, which contains:

var s = document.createElement('script');
s.src = chrome.extension.getURL('src/js/content_script_inject.js');
s.onload = function() {

And the file
, which performs the actions on the webpage itself. In my injected content script, I am waiting for the

function onYouTubePlayerReady(playerId) {
foo(); // <-- function not defined, error does not show in console
foo(); // <-- error shows in console

If a runtime error is caused by, e.g., calling a function that does not exist such as
in the above case, I do not see this error on the console when it is called from inside that function.

So: How can I catch errors generated in this JavaScript while programming it? I am assuming it is because the function is called from YouTube JavaScript instead…?

Xan Xan

An error is called a runtime error, if, well, it happens when the code is run.

Your script only declares onYouTubePlayerReady but does not actually run it (it's supposed to be run by something else later). As such, you can't see runtime errors: there aren't any. Yet.

Syntax errors, in contrast, are parse-time errors. As such, you'll see them regardless.

Note that in your particular case, the fact that you don't see errors probably means YouTube API either already tried to invoke the function, or never actually tries. You may want to set run_at content script parameter to "document_start" to exclude the first possibility.

If you are sure that the code gets executed, it's potentially possible that the page (or YT API) has a global exception handler that silences runtime errors. In this case, you can try to include try...catch in your code to catch and log exceptions before they bubble up.