-1

A web page uses an external script:

<script src="script/alerts.js" type="text/javascript"></script>

In this script file there is a function which I would like to modify/replace. The function looks like this:

function SayHello(msg1, msg2){
    alert(msg1);
    alert(msg2;
    // just saying hi and doing something i don't want to
}

I want to change it into something like this:

function SayHello(msg1, msg2){
    // not saying hello
    // but i'm doing everything i want to
}

How can i do this without using unsafeWindow?

Note: the function must be executed in the content page scope, rather than in the Greasemonkey sandbox.

Dani
  • 39
  • 1
  • 5
  • possible duplicate of [Changing Javascript on an HTML page out of my control](http://stackoverflow.com/questions/10472569/changing-javascript-on-an-html-page-out-of-my-control) – Brock Adams Sep 25 '13 at 04:02
  • Also a duplicate of [Stop execution of Javascript function (client side) or tweak it](http://stackoverflow.com/q/3972038/331508). – Brock Adams Sep 25 '13 at 04:03

2 Answers2

2

As simple as that:

location.assign("javascript:void(SayHello = function () {})");

It works even if you need to use any GM_* function. (@grant)

w35l3y
  • 8,613
  • 3
  • 39
  • 51
  • 1
    This works, but **only if `SayHello()` is global scope** -- which is not clear from the question. – Brock Adams Sep 25 '13 at 04:04
  • The script must be executed in the content page scope, rather than in the Greasemonkey sandbox. I've started learning javascript/HTML about 1 year ago. Sorry for not being fully clear about what i need to do, it's not cause i don't want to. I will try [this](http://stackoverflow.com/questions/10472569/changing-javascript-on-an-html-page-out-of-my-control) as soon as i get home and i will let you know – Dani Sep 25 '13 at 15:49
  • @Dani, By "content page", you mean "target page". This answer does that via the "location hack". The only drawback is that `SayHello` must be in the target page's global scope. It might be; give it a try. – Brock Adams Sep 26 '13 at 01:03
  • @BrockAdams always with pertinent considerations. Thanks – w35l3y Sep 26 '13 at 01:21
0

you cannot do something against unsafeWindow unless you run your code within the unsafe window.

what you can do however is redefining the method like:

SayHello = function (msg1, msg2){
    // not saying hello
    // but i'm doing everything i want to
}

it will replace the original function with this one.

you should also keep in mind that you cannot break into closures just using greasemonkey and that you cannot replace methods that have been copied into local variables the moment the script first ran through.

GottZBot
  • 9
  • 2