Search code examples
javascripthtmlcode-injection

How to inject JavaScript into a website through the URL bar?


Here is the JavaScript code I inject into the page:

javascript:{document.head.innerHTML+='<script>function inject(){alert("hello");}</script>';
document.body.innerHTML+='<button onclick="inject()">Run</button>';}

After running this code in the URL bar, I inspect the source code of the website. Both the button and the function definition are present, however pressing the button does not run the alert as one would expect.

What could be the problem?


Solution

    1. some browsers no longer accept javascript: directly from the location bar, they need you to call the script from a bookmarklet

    2. your syntax smells of wishful thinking. What you try here would never work that way

    This syntax:

    javascript:(function() { var s = document.createElement("script"); s.src="somejsurl.js";document.getElementsByTagName("head")[0].appendChild(s)})()
    

    might be a better start

    To get this to execute, you would need to create an html page with

    <a href="javascript:(function() { var s = document.createElement('script'); s.src='somejsurl.js';document.getElementsByTagName('head')[0].appendChild(s)})()">Exec</a>
    

    using single quotes inside the href code and load and drag the "Exec" to the bookmarks

    While testing, Chrome and Firefox has a command line you can use

    If you want to create the script and not load it, you would need to inline the script in the button you created:

    javascript:(function() { var b = document.createElement("button"); b.onclick=function() { alert('hello')}; b.innerTHML='Hello';})()