0

I was wondering if we can add data to a function which is already defined in Javascript.

    var win;
    window.onload= function()
    {

        win = window.onbeforeunload;
        win = win.toString();

        var firstLetter = win.indexOf('{');


        win = win.substring(firstLetter + 1, win.length - 1);
        //Getting the data of the function [firstLetter = first occurrence of { ]

        win = win + 'alert("More Unload");';

        `/* Here, I want to rebind var win to the window.onbeforeunload event*/`
    }   

    window.onbeforeunload = function () 
    {
        alert("Unload function");
        alert("More Unload");
    }

Is this possible?

Thanks.

1 Answer 1

1

You can create a function using new Function(yourCodeString).

However, this kind of code rewriting is extremely messy and if you need it you are doing something wrong for sure!

Sign up to request clarification or add additional context in comments.

2 Comments

Ok. See I am writing a plugin that has an onbeforeunload function. I want to be sure that my onbeforeunload doesn't collide if there is one on the page where my plugin would be integrated.
At least firefox doesn't even show the message provided in onbeforeunload. And using alert() in that function sounds super-annoying since it will be two popups the user will have to click away.

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.