簡體   English   中英

從 URL 執行網頁內的 javascript 函數?

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

我有這個 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>

然后我將此代碼保存為: C:/js.html

然后我在瀏覽器的地址欄中寫下:

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

但是沒有執行 Javascript 函數。 為什么?

我怎樣才能使這項工作?

試試這個短片。 使用#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();

你需要像這樣把你的腳本標簽放在頭標簽之間

<!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>

這就是你要求的

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

恭喜! 你剛剛造成了一個 XSS 漏洞。 當心 site.html#deleteuseraccount()

更好的方法來做到這一點,但錯誤的回答你的問題。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM