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

谁说我不能喝 提交于 2019-12-05 08:13:26

问题


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?


回答1:


  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';})()



回答2:


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



来源:https://stackoverflow.com/questions/19078810/how-to-inject-javascript-into-a-website-through-the-url-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!