简体   繁体   中英

Executing document's Javascript function by using third-party Javascript?

Say I have localhost/site/index.php with one Javascript function and one button:

<html>
<head>
    <meta charset="utf-8" />
    <title>Page Title</title>
<script type="text/javascript">
    function my_function(){
        alert('Hello eveeryone!');
    }
</script>


</head>

<body>

<button type="button" onclick="my_function();" />Here is my button</button>

</body>
</html>

Is there a way to execute my_function() without clicking button - by using some kind of bookmarklet or similar kind of in-browser residing Javascript or anything else that not implies clicking on button-default interacting with document's Javascript?

EDIT: Better explanation of problem: can I use localhost/site/script.php to trigger above mentioned my_function that resides in localhost/site/index.php?

您可以使用主体onload功能:

<body onload="my_function();">

You can use jQuery trigger.

$('button').trigger('click')

The button's onclick handler gets called. (Actually ALL buttons' onclick handlers are called. So maybe make a class or id for the specific button to target it)

I'm assuming that the web page is not yours so you can't modify it directly. So, if you have a way of executing javascript in the context of the page (bookmarklet or plug-in or something like that) and you know what the name of the click handler function is, then you can just execute the click handler directly with:

my_function()

EDIT: because now it appears from comments that you are actually asking a question about the security of your own web page.

You cannot prevent the execution of javascript functions in your own web page. There are numerous ways for people to inject code into your page from their own browser that can call anything in your web page that is globally accessible. You cannot prevent that. It's possible to make it more difficult to directly call event handlers, but this just makes it slightly more work, but does not prevent it.

Security MUST be implemented on your server - it cannot be implemented in a web page. A browser client web page is NOT a secure environment. It can be freely modified. Whatever you are trying to protect from must be implemented on the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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