Override window.confirm() confirmation through chrome extension?

Viewed 1311

To simplify the example, let us say I have the following web page:

<html>
<input type="button" value="click me!" onclick="Confirmation()">
</html>

<script>
    function Confirmation() {

        if (window.confirm("Are you sure you want to proceed?")) {
            alert("proceeded!");
        }
    }
</script>

What I am trying to do is inject my chrome extension in a way that it would either override the confirmation() function,
or would change it to the following:

<script>
    function Confirmation() {

        if (true) {
            alert("proceeded!");
        }
    }
</script>

how could I achieve that?


Edit:

This is the solution that worked with me:

@elegant-user 's function

var jsCodeInjection = '' + function Confirmation() {
    if (true) {
            alert("proceeded cs!");
        }

} + '';
var script = document.createElement('script');
script.textContent = jsCodeInjection;
(document.body||document.documentElement).appendChild(script);
script.remove();

If you want a cleaner way of implementing it, then:

@Kaiido 's referral for how to inject a seperate .js file for a cleaner implementation:

Insert code into the page context using a content script

If the script element has multiple functions, and you're trying to override one(or some) of them,
then you have to copy all the functions in a separate js file, and adjust the functions that you want to adjust.

3 Answers

Less desired but you can try the below code in your content script:

var jsCodeInjection = '' + function Confirmation() {
    if (true) {
            alert("proceeded cs!");
        }

} + '';
var script = document.createElement('script');
script.textContent = jsCodeInjection;
(document.body||document.documentElement).appendChild(script);
script.remove();

If you can inject code in the page, then you just need to overwrite window#confirm() method:

(()=>{
  const c = window.confirm;
  window.confirm = (...args) => {
   c.apply(window, args);
   return true;
  }
 })();

console.log(confirm('works?'));

Note that overwritting default methods like this is not recommended, but neither is using window.confirm()...

Put the below function code in your content.js file and call the function.When you call this function After that no confirmation box will be shown/appear.

content.js below is the function code

const overrideConfirmBox=()=>{
    let myScript=document.createElement("script");
    myScript.innerHTML=`window.confirm=(...args)=>{ return true; }`;
    document.body.appendChild(myScript);
}

content.js call the above function

overrideConfirmBox()
Related