套接字.在Phonegap移动应用程序中未定义的变量

Socket.io variable not defined in Phonegap mobile application

本文关键字:未定义 变量 应用程序 Phonegap 移动 套接字      更新时间:2023-09-26

我正在尝试使用Phonegap与RequireJs, Backbone, jQuery开发一个移动应用程序,每次我试图包括requirejs脚本标签时,我都会遇到一个问题:

<script data-main="js/app" src="node_modules/requirejs/require.js</script>

在包含这个之后,我得到以下错误:

ReferenceError: io is not defined.

我没有使用socket.io,但我认为Phonegap正在使用它来刷新浏览器中的页面。

这是我的index.html文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
    <title>Hello World</title>
</head>
<body>
    something nice
    <!-- Content -->
    <script type="text/javascript" src="cordova.js"></script>
    <script data-main="js/app" src="node_modules/requirejs/require.js"></script>
</body>
</html>

这是我的js/app.js文件:

requirejs.config({
    baseUrl: 'js',
    shim: {
        'socket.io': {
            exports: 'io'
        },
        'underscore': {
            exports: '_'
        },
        'backbone': {
            deps: [
                'underscore',
                'jquery'
            ],
            exports: 'Backbone'
        }
    },
    paths: {
        jquery: 'jquery.min',
        underscore: 'lodash.min',
        backbone: 'backbone',
        socketio: '../socket.io/socket.io'
        // package: 'node_modules'
    }
    // map: {
    //
    //     '*': {
    //         'jquery': 'private/jquery'
    //     },
    //
    //     'private/jquery': {
    //         'jquery': 'jquery'
    //     }
    // }
});

我使用的是Phonegap 6.3.4版本

你能告诉我,我该怎么做才能摆脱这个错误吗?

谢谢!

我已经通过阅读这些文章解决了这个问题:

  • 有Phonegap集成插座。IO在3.5.0-0.20.10版本?
  • https://github.com/phonegap/phonegap-app-developer/issues/339
  • 不匹配的匿名定义()模块

这是我的解决方案:

<script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript">
        // Fixes "Uncaught ReferenceError: io is not defined".
        // We need to load RequireJs after socket.io has been loaded.
        function injectRequireJs() {
            var h = document.getElementsByTagName('body')[0];
            var s = document.createElement('script');
            s.type = 'text/javascript';
            s.src = 'node_modules/requirejs/require.js';
            s.setAttribute('data-main', 'js/bootstrap');
            h.appendChild(s);
        }
        setTimeout(function(){
            injectRequireJs();
        }, 1);
    </script>