Is it possible to inject a javascript code that OVERRIDES the one existing in a DOM? (e.g default alert function)

Functions don’t exist as part of the DOM; instead, they exist within an execution environment that includes the DOM. Content scripts (including scripts run with executeScript) and actual web pages share the same DOM, but have separate execution environments. So calling window.alert = function() {} only rewrites window.alert within your content script’s execution environment, not in the actual page’s one.

The typical way to reach the execution environment of the actual page is to inject a <script> tag into the DOM. This can be done in several ways. One method is to white-list a script in web_accessible_resource, and insert the <script> element referring to this script in the document. The required absolute URL can be obtained via chrome.extension.getURL.

var s = document.createElement("script");
s.src = chrome.extension.getURL("script_in_extension.js");
(document.head||document.documentElement).appendChild(s);

Make sure that the script is configured to "run_at": "document_start", so that the overwrite takes place before any of the page’s functions are loaded.

Note: Your action can easily be undone by the page:

window.alert = function(){ /*...*/ }; // Your overwrite
delete window.alert;                  // Run from the page/console/...
window.alert('Test?');                // Displays alert box.

If it’s critical that the overwritten function cannot be removed, use Object.defineProperty to define an immutable method. For more details, see Stop a function from execute with Chrome extension.

Leave a Comment