
function  injectChromeRuntimeIntoFirefox() {
    if (typeof browser === "undefined") {
        // we are in Chrome
        return false;
    }

    // injecting polyfill to make it work in FF the old way
    const injectedCode = '(' + function() {
        if (typeof chrome === 'undefined') {
            (function() {

                // redefine global CHROME variable
                const registeredCallbacks = {};
                chrome = {
                    runtime: {
                        sendMessage: function (pluginId, message, callback) {
                            const messageId = Math.random();
                            window.postMessage({
                                type: "to_kolotibablo_extension",
                                pluginId: pluginId,
                                messageId: messageId,
                                message: message
                            }, "*");
                            registeredCallbacks[messageId] = callback;
                        }
                    }
                }

                window.addEventListener("message", function (event) {
                    if (event.data.type
                        && event.data.type == "from_kolotibablo_extension") {

                        if (typeof event.data.messageId !== 'undefined') {
                            if (typeof registeredCallbacks[event.data.messageId] !== 'undefined') {
                                registeredCallbacks[event.data.messageId](event.data.message);
                                delete registeredCallbacks[event.data.messageId];
                            }
                        }
                    }
                });

            })();
        }
    } + ')();';
    const script = document.createElement('script');
    script.textContent = injectedCode;
    (document.head || document.documentElement).appendChild(script);


    window.addEventListener("message", function(event) {
        if (event.source !== window) {
            return;
        }
        if (typeof event.data !== 'undefined'
            && typeof event.data.type !== 'undefined'
            && event.data.type == "to_kolotibablo_extension") {

            // passing message to a Background as is
            chrome.runtime.sendMessage(event.data, function (message) {
                if (typeof event.data.messageId !== 'undefined') {
                    window.postMessage({ type: "from_kolotibablo_extension", messageId: event.data.messageId, message: message }, "*");
                }
            });
        }

    }, false);
}

export { injectChromeRuntimeIntoFirefox }