1

The loaded page html include a js function:

<html>
....
<body>
  <script>
  function test(){
    alert("I'm master");
   //here is the page original funciton
  }
  </script>
</body>
</html>

And i want to write a chrome extension load my customize js file replace the current page js function test() ,for example :

new function name =>  
function test() {
    alert("I'm a new function come my chrome extension ");
}

what should i do?

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
cow
  • 398
  • 4
  • 12

1 Answers1

3

Inline scripts are executed by Chrome immediately, you won't be able to prevent them from running. And we can't modify html before it's parsed: chrome extension - modifying HTTP response.

Your only chance is that the function is only declared, but not being called immediately by the page script. In this case a working solution exists.

Declare a content script that will inject <script> element with the new function declaration:

  • manifest.json

    "content_scripts": [{
        "matches": ["http://somedomain.com/blabla*"],
        "js": ["content.js"]
    }],
    
  • content.js

    document.body.appendChild(document.createElement('script')).text =
        getFunctionCode(function() {
            function test() {
                alert("I'm a new function from my chrome extension");
            }
        });
    
    function getFunctionCode(fn) {
        return fn.toString().match(/\{([\s\S]*?)\}$/)[1];
    }
    

See also: a great answer about injecting page-level scripts.

Community
  • 1
  • 1
wOxxOm
  • 65,848
  • 11
  • 132
  • 136