1

I have following script tag where a function A() does a document.write(). I don't have access to A() since it's from third part script.

//block1
<script type="text/javascript">
    A();
</script>

I don't have any id/class hook to block1 but I can introduce a function call before A() like this.

<script type="text/javascript">
     B();
     A();
</script>

I want B() function to replace block1 to

<script type="text/javascript">
     C();
</script>    
// or keep as is
<script type="text/javascript">
     A();
</script>

Is this possible and how should I go about it?

2 Answers 2

4

If you can insert code after A() is defined, but before it is called (might not be possible), then you can redefine A() like you would define any other function in JavaScript.

If that is not possible, you can redefine document.write before A() gets called, and then undo that after A() gets called. For example:

var write = document.write;
document.write = function(s)
{
    //do nothing, or whatever you want
    console.log(s);
}
//then, after A(), just do:
document.write = write;
Sign up to request clarification or add additional context in comments.

2 Comments

+1 this is kinda useful. Although one issue is B() might replace the block with A(). In above example, A() will be called again which I don't want.
thanks wsanville , this was really useful for some script I was using that was copying and replacing a html block that had a document.write in it. fixed now after seeing this.
0

Perhaps you can monkey-patch A instead?

A = C;

This will change all future calls to A to call C instead. This might or might not be what you want.

3 Comments

thanks for chipping in. A() is called multiple times on the page, hence rules this out.
Is it recursively called though? There is also the possibility of doing oldA = A; A = C; A(); A = oldA
+1 It's not but I can't remove A(); and can only add B();. Above solution will make it execute twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.