How to inject JavaScript into a website through th

2020-06-30 06:01发布

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?

2条回答
Fickle 薄情
2楼-- · 2020-06-30 06:16

Some browsers have decided to limit javascript use in the URL bar for security purposes...

查看更多
冷血范
3楼-- · 2020-06-30 06:32
  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';})()
查看更多
登录 后发表回答