简体   繁体   English

从 URL 执行网页内的 javascript 函数?

[英]Execute javascript function inside web-page from URL?

I have this HTML code:我有这个 HTML 代码:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box:</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>

</body>
</html>

Then I save this code as: C:/js.html然后我将此代码保存为: C:/js.html

Then I write in the address-bar of my browser:然后我在浏览器的地址栏中写下:

file:///C:/js.html#javascript:myFunction(); file:///C:/js.html#javascript:myFunction();

But the Javascript function is not executed.但是没有执行 Javascript 函数。 Why?为什么?

How can I make this work?我怎样才能使这项工作?

Try this short snipped.试试这个短片。 Visit your page with #test as location part of your url index.html#test.使用#test 作为url index.html#test 的位置部分访问您的页面。

function myHash() {
    alert('here iam!');
}

function hash() {
    var hash = location.hash;

    switch(hash) {
        case '#test' : myHash();
            break;
        default : break;
    }
}

hash();

you need to put your script tag between the head tags like so你需要像这样把你的脚本标签放在头标签之间

<!doctype html>
<html>
<head>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>
</head>
<body>
<p>Click the button to display an alert box:</p>

<button onclick="myFunction()">Try it</button>
</body>
</html>

This is what you asked for这就是你要求的

<script type="text/javascript">
if(window.location.hash)
eval(window.location.hash.substr(1))
</script>

Congratulation!恭喜! You just caused an XSS vulnerability.你刚刚造成了一个 XSS 漏洞。 Beware of site.html#deleteuseraccount()当心 site.html#deleteuseraccount()

Better way to do it but wrong answer to yourr question.更好的方法来做到这一点,但错误的回答你的问题。

<script>
function() {
    if (location.hash === "#magicword") {
    YourMagicHere();
 }};
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM