4

I am trying to build a chrome extension; minimal experience in this area. I have followed Insert code into the page context using a content script to inject js code into pages using the first method.

I'm trying to build a js framework over someone else's code which relies heavily on alerts which are breaking the functionality of my overlay, so I just want to silence them for a bit--actually, I'd rather pass the messages into console.log but I'll take what I can get at this stage. So I've tried to follow JavaScript: Overriding alert() in setting up my eventual js file (nogo.js) to be injected.

nogo.js is injected but it doesn't seem to have the effect of suppressing the alerts. could it be that because the other html file is itself being initiated by a different js file that the injection is happening too slowly or out of order?

Manifest.json

  "content_scripts": [
        {
          "matches": ["*://URL/*"],
          "js": ["myscript.js"],
          "run_at": "document_end",
          "all_frames": true
        },
        {
          "matches": ["*://URL/*"],
          "js": ["noalerts.js"],
          "run_at": "document_start",
          "all_frames": true
        }

      ],
       "web_accessible_resources": ["script.js","nogo.js"]

     }

myscript.js

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

noalerts.js

var n = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
n.src = chrome.extension.getURL('nogo.js');
n.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(n);

nogo.js

window.alert = null;
Community
  • 1
  • 1

1 Answers1

5

To make alert do nothing, just paste the lines to override it:

var s = document.createElement('script');
s.innerHTML = "alert = function(){}"
document.body.appendChild(s);

The function will be redeclared with you function body. I've had to do similar things in my extensions.

By analogy you can make confirm function say "yes" everytime:

var s = document.createElement('script');
s.innerHTML = "confirm= function(){return true;}"
document.body.appendChild(s);

That can be used for the simplest cases.. For example, noone else does anything else on the page, etc.

Notice: you can try this approach by pasting the code in the console and trying to invoke alert. Notice 2: the code can be executed in your content-script because the document it shared between its scripts and your content scripts.

Noam Hacker
  • 4,671
  • 7
  • 34
  • 55
Dzmtrs
  • 426
  • 3
  • 5