Ошибка ссылки при вызове функции во внешней библиотеке - только для Firefox

Я использую Geoplugin для получения данных о пользователе, отправляющем форму для подписки на информационный бюллетень.

В Chrome и Safari работает хорошо. С другой стороны, Firefox выдает ReferenceError: geoplugin_request is not defined

Почему Firefox ведет себя иначе? Как это исправить? Спасибо

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WEHMIX</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/stile.css">
    <!--<script src="http://www.geoplugin.net/javascript.gp"></script>-->
    <script src="http://www.geoplugin.net/javascript.gp"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-10 col-sm-offset-1 text-center">
                <h1 class="title-box">wehmix</h1>
                <h3>Rimani in contatto con il progetto wehmix.</h3>
                <p>Iscriviti alla newsletter per essere aggiornato in anteprima sull'evoluzione del progetto, per partecipare agli incontri di presentazione e far parte della ricerca.</p>
                <form id="contatto" method="post" action="https://anypoint.mulesoft.com/apiplatform/proxy/https://mocksvc.mulesoft.com/mocks/4790cf82-7131-46a1-b427-562e4e8f22ce/newsletter/subscriber">
                    <input id="email" name="email" type="text" placeholder="Inserisci la tua e-mail" value="">
                    <input type="submit" value="Iscriviti">
                </form>
                <p class="feedback"><i class="glyphicon glyphicon-thumbs-up"></i></p>
            </div>
        </div>
    </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

JS

var request;

$("#contatto").submit(function(e){
    // Abort any pending request
    if (request) {
        request.abort();
    }

    // Retrieve email
    var $email = $('#email').val();

    // Take data available from navigator object
    var $ip = geoplugin_request();
    var $browserCodeName = navigator.appCodeName;
    var $browserName = navigator.appName;
    var $browserVersion = navigator.appVersion;
    var $language = navigator.language;
    var $platform = navigator.platform;
    var $city = geoplugin_city();
    var $region = geoplugin_regionName();
    var $country = geoplugin_countryName();

    // Prova stampa valori geocode
    console.log($city);
    console.log($region);
    console.log($country);

    // Create the JSON structure
    var user = {};
    user['user_agent'] = {};

    user.email_address = $email;
    user.user_agent.ip = $ip;
    user.user_agent.browserCodeName = $browserCodeName;
    user.user_agent.browserName = $browserName;
    user.user_agent.browserVersion = $browserVersion;
    user.user_agent.language = $language;
    user.user_agent.platform = $platform;
    user.user_agent.city = $city;
    user.user_agent.region = $region;
    user.user_agent.country = $country;

    var finalJson = JSON.stringify(user);

    console.log(finalJson);

    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input");

    // Serialize the data in the form
    //var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        type: "post",
        url: "https://anypoint.mulesoft.com/apiplatform/proxy/https://mocksvc.mulesoft.com/mocks/4790cf82-7131-46a1-b427-562e4e8f22ce/newsletter/subscriber",
        contentType: "application/json; charset=utf-8",
        data: finalJson
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        $('.feedback').text('Iscrizione completata con successo!');
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error("The following error occurred: "+textStatus, errorThrown);
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    e.preventDefault();
});

person The Condor    schedule 06.06.2016    source источник


Ответы (1)


Может быть состояние гонки. Вы загружаете и скрипт геоплагина, и собственный обработчик событий. Если геоплагин должен загружаться дольше, чем ваш собственный скрипт, и вы достаточно быстро отправляете форму, возможно, глобальный geoplugin_request еще не доступен. Кажется странным, что скрипту требуется так много времени, но с собственным скриптом, доступным локально, и другим в другом месте, это возможно.

Ваши теги говорят, что вы используете jQuery, поэтому вы можете загрузить геоплагин через функцию $.getScript() и зарегистрировать обработчик кликов в анонимной функции, указанной в качестве второго параметра:

$.getScript("http://www.geoplugin.net/javascript.gp", function () {
  $("#contatto").submit(function(e){ ... }
});

Более элегантным решением было бы использование инструмента загрузки модулей, который обрабатывает такие зависимости, как RequireJs.

person JSchirrmacher    schedule 06.06.2016
comment
Я попробовал ваше решение, и хотя оно работает в Firefox, оно больше не работает в Chrome! Это дает ту же ошибку, что и Firefox до этого изменения. - person The Condor; 06.06.2016
comment
Это странно. Я попытался воспроизвести вашу проблему, используя jsfiddle.net, но обнаружил, что геоплагин не полностью поддерживает зашифрованные соединения (https), которые требуются jsfiddle. Не удалось загрузить. Может быть, ваша среда тоже на https? - person JSchirrmacher; 06.06.2016
comment
Нет, но, кажется, я разобрался. Моя проблема, вероятно, связана с Iceweasel, версией Firefox для Debian. Почему-то он не загружает функции/переменные из внешней библиотеки, тогда как оригинальный Firefox работает без нареканий. Спасибо за вашу помощь в любом случае! - person The Condor; 06.06.2016