user1580348
user1580348

Reputation: 6051

Execute javascript function inside web-page from URL?

I have this HTML code:

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

Then I write in the address-bar of my browser:

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

But the Javascript function is not executed. Why?

How can I make this work?

Upvotes: 1

Views: 6247

Answers (3)

user23139
user23139

Reputation: 368

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. Beware of site.html#deleteuseraccount()

Better way to do it but wrong answer to yourr question.

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

Upvotes: 0

user4164128
user4164128

Reputation:

Try this short snipped. Visit your page with #test as location part of your url index.html#test.

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

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

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

hash();

Upvotes: 2

hello world
hello world

Reputation: 1755

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>

Upvotes: 0

Related Questions