PinkTurtle
PinkTurtle

Reputation: 7041

dyamically appended javascript file throws; is it possible to catch?

In file2.js I have:

throw new String("oops");

In file1.js I have:

document.head.appendChild(dynamically_created_file_2_script_element);

How can I catch the string thrown in file2.js?

I have tried:

try {
    document.head.appendChild(dynamically_created_file_2_script_element);
}
catch(err) { ... }

to no avail. Also, the onerror event listener on dynamically_created_file_1_script_element is of no use here.

Upvotes: 1

Views: 39

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370889

Before appending the script, you can add an error listener to the window.

The error event is fired on a Window object when a resource failed to load or couldn't be used — for example if a script has an execution error.

Inside the handler, you can check which resource resulted in the error by looking at the filename property of the event.

window.addEventListener('error', (errorEvent) => {
    if (errorEvent.filename.endsWith('file2.js')) {
        console.log('Saw error from file2.js:')
        console.log(errorEvent.message);
    }
});

document.body.appendChild(document.createElement('script')).src = './file2.js';

Note that this can only work if the script is on a live server, and on the same domain. Due to cross-origin restrictions, in other situations, the only info available will be Script error.

Upvotes: 1

Related Questions