Search code examples
javascriptfunctionbookmarklet

How to modify a function in a page using Bookmarklet?


Lets say I have an HTML page which has its own function myFunction()

<!DOCTYPE html>
<html>
<body>

<p>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

<script>
function myFunction() {
    alert("stack overflow");
    document.getElementById("demo").innerHTML = "Hello World";
}
</script>

</body>
</html>

I want to change the myFunction()definition like this

function myFunction() {
    //alert("stack overflow");
    document.getElementById("demo").innerHTML = "Hello World";
}

using bookmarklet.So is there any way to change the def temporarily ? I tried using the Chrome Console to change its def and also remain successful,but I want to change it using bookmarklets.So please help me.


Solution

  • As it's a global, you can do this in your bookmarklet:

    var oldFunction = myFunction;
    myFunction = function() {
        alert("Hello world!");
    };
    

    Or if you enclose your bookmarklet in a scping function (usually a good idea), probably store the old value on a window property instead of a local var (so you can access it from another bookmarklet to restore it later):

    window.oldFunction = myFunction;
    myFunction = function() {
        alert("Hello world!");
    };
    

    Another bookmarklet could set it back again:

    myFunction = window.oldFunction; // or just = oldFunction if using a local var
    

    Live Example:

    function myFunction() {
      alert("Original function");
    }
    document.getElementById("btn-override").addEventListener("click", function() {
      window.oldFunction = myFunction;
      myFunction = function() {
        alert("New function");
      };
    }, false);
    document.getElementById("btn-restore").addEventListener("click", function() {
      myFunction = window.oldFunction;
    }, false);
    <input type="button" id="btn-call" value="Click to call myFunction" onclick="myFunction()">
    <input type="button" id="btn-override" value="Click to override it">
    <input type="button" id="btn-restore" value="Click to restore it">