We will discuss three methods to accomplish this task, each following the same approach but with different implementations to extract useful information. Choose the method that suits your specific use case.
Method 1: window.addEventListener(“error”, yourErrorLoggerFunction)
- Attach an error event to the window object (DOM).
Method 2: document.querySelector(‘body’).onerror = yourErrorLoggerFunction
- Use an error listener in the body tag, which works for both same origin and cross-scripts of the same origin.
Method 3: Create a script element and append it to the body tag of the source.
All three methods can be implemented in either the same or external sources.
Note: It is crucial to ensure that this code is executed first by the browser. If unsure, it is strongly recommended to use Method 2.
Method 1: Event Listener on Window Object
In this method, we attach an event listener to the window object. When a script error occurs, the attached error logger function is triggered. Inside the error logger function, we extract all the useful information from the event object received.
HTML Code (Method 1):
Method 2: Using
onerror Event Handler
In this method, we make use of the
onerror event handler.
- Step 1: Get the body tag of the HTML markup, either from an external source or the currently loaded page.
- Step 2: Add the
onerrorevent handler to the body tag.
Did you notice the difference in the logger function between the two methods? Typically, when an event is fired, the attached function receives an event object. However, in Method 2, we receive pre-extracted information. Refer to MDN WebDocs for detailed reasons.
Note: Pay attention to the order of error information received in the logger function. A total of 5 pieces of information are provided, and the sequence remains consistent.
HTML Code (Method 2):
Method 3: Attaching a Script Element
In this method, we attach a script element to the webpage. This approach is useful when we want the error logger to activate at a specific time or for executing external scripts.
- Step 1: Retrieve the body tag of the target markup page.
- Step 2: Prepare a script element and append it.
Explanation of Example (Method 3):
As you can see, we have used an iframe to access
index.html, which is on the same page (same origin). We planted a script in the parent page to log errors in another webpage.
Warning: Be cautious when using these methods for cross-scripting (CORS) with scripts from different origins. Ensure that you have written permission from the owner of the page.
HTML Code (Method 3):
- You can use both
innerTextto avoid any unwanted errors caused by HTML entities.
- In Method 3, the target and the way of obtaining it may vary in different cases. Thus, the implementation code for this method might differ slightly, but the approach remains the same.
So, implement these methods and ensure a seamless user experience on your website!