Regis / Wofh Linker Addon

// ==UserScript==
// @name         Wofh Linker Addon
// @namespace    https://ru.waysofhistory.com/
// @version      0.5
// @description  Enables copying of game links and helps the game to open them.
// @author       Regis
// @match        https://*.waysofhistory.com/
// @match        https://*.waysofhistory.com/gen/html/*
// @grant        unsafeWindow
// @grant        window.close
// @grant        window.focus
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // Stopflag to turn the addon off if needed
    if (unsafeWindow.disableWofhLinkerAddon) {
        return;
    }

    // This way game can know that user has the addon
    unsafeWindow.wofhLinkerAddon = true;

    if (window.location.pathname === '/' && !window.title && window === window.top && !unsafeWindow.jQuery) {
        // Seems like we on the "error: 9" page
        if (document.body.innerHTML.trim().indexOf('{"error":9}') >= 0) {
            var hash = window.location.hash;
            if (hash) {
                var reportPrefix = '#/report/';
                if (hash.indexOf(reportPrefix) === 0) {
                    // Report link => just fix the link
                    window.location = '/report#' + hash.substring(reportPrefix.length);
                } else {
                    passHashToGame(hash);
                }
            }
        }
        return;
    }

    if (window.location.pathname.indexOf("/gen/html/") === 0 && window !== window.top && unsafeWindow.jQuery && unsafeWindow.HashMgr && unsafeWindow.appl) {
        // Seems like we in the game page
        setupHashMessageListener();
    }

    function passHashToGame(hash) {
        var message = JSON.stringify({
            event: 'hash_from_link',
            hash: hash,
            server: window.location.host
        });

        var bc = new BroadcastChannel('regis_wofh_linker_addon');
        bc.postMessage(message);
        bc.close();
        /*
        var e = document.createElement('div');
        e.innerHTML = "WofhLinkerAddon by Regis: Ссылка передана в игру (если она открыта).";
        document.body.append(e);
        */
        window.close();
    }

    function disableLinkHiding() {
        // Turn off the code that hides links
        // Note: that can remove some unwanted handlers too! Is there a way to remove specific handler?
        // Investigate: $._data( document, "events" ).mousedown
        // $._data( document, "events" ).mousedown[0].handler.toString() проверять на текст "Не запрещаем создания новой вкладки для боя если параметр platform.battletabs истина"
        var $ = unsafeWindow.jQuery;

        var selector = 'a';
        if (unsafeWindow.ls.getGameIf() == unsafeWindow.Appl.interface.simplified) {
            selector += ',area';
        }

        if (unsafeWindow.hashMgr) {
            // App initialized - turn off the event handler
            $(document).off('mousedown', selector);
        } else {
            // App is not ready yet. Catch listener.

            var original_onTmplLoaded = unsafeWindow.Appl3.prototype.onTmplLoaded;
            unsafeWindow.Appl3.prototype.onTmplLoaded = function () {
                original_onTmplLoaded.apply(this, arguments);
                $(document).off('mousedown', selector);
            };
        }
    }

    function setupHashMessageListener() {
        var bc = new BroadcastChannel('regis_wofh_linker_addon');
        bc.onmessage = function (ev) {
            var data = JSON.parse(ev.data);
            if (data.event === 'hash_from_link' && data.server === window.location.host) {
                //alert(data.hash);
                if (unsafeWindow.hashMgr) {
                    window.location.hash = data.hash;
                    unsafeWindow.hashMgr.parse();
                    window.focus();
                }
            }
        };
        //alert("Listener enabled");

        disableLinkHiding();
    }

})();