如何通过 URL 栏将 JavaScript 注入网站?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19078810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:16:35  来源:igfitidea点击:

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

javascripthtmlcode-injection

提问by Richard Hayes

Here is the JavaScript code I inject into the page:

这是我注入页面的 JavaScript 代码:

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.

在 URL 栏中运行此代码后,我检查了网站的源代码。按钮和函数定义都存在,但是按下按钮不会像预期的那样运行警报。

What could be the problem?

可能是什么问题呢?

回答by mplungjan

  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

  1. 一些浏览器不再接受 javascript:直接从地址栏,他们需要你从书签调用脚本

  2. 你的语法有种一厢情愿的味道。你在这里尝试的东西永远不会那样奏效

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

要执行此操作,您需要创建一个 html 页面

<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

在 href 代码中使用单引号并将“Exec”加载并拖动到书签

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

在测试时,Chrome 和 Firefox 有一个可以使用的命令行

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

回答by Benjamin Tamási

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

出于安全目的,某些浏览器已决定限制在 URL 栏中使用 javascript...