【问题标题】:Get page url from embeded JS script从嵌入 JS 脚本获取页面 url
【发布时间】:2014-09-03 16:06:09
【问题描述】:

我有一个调用 JS 文件的 HTML 页面。在那个 JS 文件中,我需要知道 HTML 页面的 URL 是什么。

到目前为止,我有这个。

HTML -

<!doctype html>
<html>
 <head>
  <title>Untitled</title>
 </head>
<body>
 <script src="js/jquery.js"></script>
 <script src="js/main.js"></script>
</body>
</html>

在我的 main.js 中,我有以下内容:

$(function() {
  $ = jQuery;
  window.remoteUser = "%globals_server_REMOTE_USER%";
  window.targetURL = "%globals_asset_url%";
  console.log(document.referrer);
});

我认为 document.referrer 会返回 html 页面的 URL。但是它会在控制台中返回一个空行。

任何帮助都会很棒。谢谢

【问题讨论】:

  • 脚本被添加到&lt;head&gt;标签内(最佳实践)
  • 不,在结束正文标记之前也是一个好习惯(性能)

标签: javascript


【解决方案1】:

试试这个,

console.log(document.URL);

console.log(window.location.href); 

因为我读到它在某些版本的 Firefox 中不起作用

【讨论】:

    【解决方案2】:

    location.href用于获取页面的url。

    jQuery(document).ready(function(){
    
           jQuery("#url1").html(location.href);   
    
    });
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多