【问题标题】:Get requested URL in Javascript在 Javascript 中获取请求的 URL
【发布时间】:2015-08-18 11:18:02
【问题描述】:

我需要在 Javascript 中找到请求的 URL(而不是当前 URL)来确定加载了两个显示站点中的哪一个。

场景:我目前正在为 Icinga Web 2 构建一个模块,该模块具有并排显示两个框架(两个单独的 .phtml 文件)的选项。当其中两个框架打开时,浏览器中显示的 URL 如下所示:

http://host/icingaweb/mymodule/siteA#!/icingaweb/mymodule/siteB

您可以通过单击其上的按钮单独重新加载单个帧。在浏览器日志(和 apache 日志)中,您可以看到,每次加载只请求特定页面:

// reloading siteA
GET http://host/icingaweb/mymodule/siteA
// reloading siteB
GET http://host/icingaweb/mymodule/siteB

我需要 Javascript 中的这个单一请求(至少是请求的站点)。

很遗憾,以下功能不起作用:

var pathname = window.location.pathname;
// returns (no matter which site is reloaded): "/icingaweb/mymodule/siteA"
var url      = window.location.href;
// returns (no matter which site is reloaded): "http://host/icingaweb/mymodule/siteA#!/icingaweb/mymodule/siteB"

Icinga Web 2 将所有 javascript 内容解析为单个文件,之后可全局访问 (icinga.min.js)。自定义 javascript 必须放在 module.js 中。

module.js

(function(Icinga) {
    var mymodule = function(module) {
       /**
        * The Icinga.Module instance (public/js/Icinga/module.js)
        */
       this.module = module;
       this.initialize();
       this.module.icinga.logger.info('mymodule module loaded');
    };

    mymodule.prototype = {
        initialize: function()
        {
            /**
             * Tell Icinga about our event handlers, these are then
             * automatically detached once Icinga is unloading
             */
            this.module.on('rendered', this.showURLs);
        },

        showURLs: function(event)
        {
            var pathname = window.location.pathname;
            // returns (no matter which site is reloaded): "/icingaweb/module/siteA"
            var url      = window.location.href;
            // returns (no matter which site is reloaded): "http://host/icingaweb/module/siteA#!/icingaweb/module/siteB"
        }
    };

    /**
     * Register this module so that Icinga knows about it
     *
     * It's important that the identifier used is the same
     * as the name of the module itself (case sensitive)
     */
    Icinga.availableModules.mymodule = mymodule;
}(Icinga));

【问题讨论】:

  • 你试过document.referrer吗?
  • @Helio document.referrer 是你来的后页的url。
  • document.referrer 返回一个空值。
  • 你在哪里查看网址,在主页还是在框架中??
  • 我正在检查脚本部分中的 url,该部分在呈现页面时由两个站点执行。我想我要编辑这个问题来告诉你怎么做。

标签: javascript jquery url get


【解决方案1】:

对于那些对解决方案感兴趣的人,Icinga Web 2 开发人员 JoNe 在monitoring-portal.org回答了我的问题

您可以使用以下方法获取当前加载的框架/页面的 URL:

$(event.target).closest('.container').data('icingaUrl')

非常感谢乔尼。

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多