wong2
wong2

Reputation: 35700

How to overwrite a function in the web page with Chrome extension?

Suppose there is a web site has a global namespace Q = {}, and there is a function under it: Q.foo

I'd like to overwrite this function in my chrome extension, so when the web page calls Q.foo, it would do what I like.

I tried to write:

Q.foo = function(){
    alert("over written");
}  

with content script. But it doesn't work....
thanks.

Upvotes: 5

Views: 4561

Answers (2)

Roderick Obrist
Roderick Obrist

Reputation: 3828

The main problem iis that a chrome extension exists in a separated enviornment which was created so that extension developers cant screw with the existing page's javascript and vice versa.

However geeky people can do this:

document.head.innerHTML += '<script>Q.foo = function(){alert("over written");}</script>';

Basically what this does is that it appends a script tag into the dom which is then instantly eval'd in the context of the page.

Upvotes: 6

Pheonix
Pheonix

Reputation: 6052

Q.prototype.foo = function(){
  alert("over written");
}

Upvotes: 1

Related Questions