在 Javascript 中获得请求 URL

Get requested URL in Javascript

我需要在 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));

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

回答了我的问题

您可以使用以下方法获取当前加载的 frame/pages 的 URL:

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

非常感谢 JoNe。