从URL /地址栏调用Javascript函数

问题描述 投票:90回答:8

是否可以从URL调用javascript函数?我基本上试图在我无法访问源的页面中利用JS方法。

像:http://www.example.com/mypage.aspx?javascript:printHelloWorld()

我知道如果你将javascript:alert("Hello World");放入地址栏就行了。

我怀疑答案是否定的,只是想知道是否有办法做到这一点。

javascript url
8个回答
54
投票

没有超链接,没有。除非页面内部专门为此设置了脚本并且它正在检查某些参数....但是对于你的问题,不,在浏览器中没有内置的支持。

然而,有bookmarklets你可以加入书签,从你的地址栏快速运行JavaScript函数;不确定这是否符合您的需求,但它尽可能接近。


19
投票

写在地址栏中

javascript:alert("hi");

确保你在开头写:javascript:


11
投票

您可以使用数据URI。例如:data:text/html,<script>alert('hi');</script>

欲了解更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs


6
投票

/test.HTML#alert('和恶劣咯)

test.html
<button onClick="eval(document.location.hash.substring(1))">do it</button>

4
投票

您也可以放置以下内容

<a href='javascript:alert("hello world!");'>Click me</a>

到您的HTML代码,当您点击“点击我”超链接时,javascript将显示在url-bar中,并且“警告”对话框将显示


2
投票

你可以像这种情况一样使用:例如,你有一个页面:http://www.example.com/page.php然后在那个page.php中,插入这段代码:

if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}

然后,每当你访问这个网址:http://www.example.com/page.php?doaction=blabla

然后会自动调用警报。


2
投票

关于window.location.hash财产: 返回URL的锚点部分。


Example 1:
//Assume that the current URL is 

var URL = "http://www.example.com/test.htm#part2";

var x = window.location.hash;

//The result of x will be:

x = "#part2"

例2:

$(function(){   
    setTimeout(function(){
        var id = document.location.hash;
        $(id).click().blur();
    }, 200);
})

例3:

var hash = "#search" || window.location.hash;
window.location.hash = hash; 

switch(hash){   
case "#search":  
    selectPanel("pnlSearch");
    break;    
case "#advsearch":    

case "#admin":  

}

1
投票

使用Eddy的答案非常有效,因为我遇到了同样的问题。只需使用以下参数调用您的网址:“www.mypage.html#myAnchor”

然后,在mypage.html中:

$(document).ready(function(){
  var hash = window.location.hash;
  if(hash.length > 0){
    // your action with the hash
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.