草庐IT

javascript - 无法与 Cordova 应用程序中的任何内容进行交互

coder 2023-12-09 原文

我无法从我的第一个 Cordova 项目中获得任何类型的交互性。我有 HTML、Javascript 和 CSS 方面的经验,所以我认为 Cordova 是混合应用程序开发的完美介绍,但我似乎连一个基本的 HTML 按钮都无法在该应用程序上运行。

我正在使用安装了 Android Studio 和 Cordova 的 Windows 10。我想我已经正确设置了项目文件结构。我一直在关注 Cordova 的文档,并在所有设备类型上安装了地理定位插件。为了进行测试,我同时使用了 Android Studio 中的虚拟安卓设备和安卓手机 (OnePlus X),它已正确连接(只要我在控制台中键入“cordova run android”,应用程序就会在手机上打开)。

我开始尝试获取我的当前位置,然后显示坐标作为警报。这不起作用,所以为了尝试更简单的方法,我添加了一个按钮,单击该按钮时应显示警报弹出窗口,但两者均无效。这是我当前的代码:

www/index.html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
        <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">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>
    </head>
    <body>  
        <div class="app">
            <h1 id="headertext">My first Cordova App!</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received" id="geolocation">Device is ready!</p>
            </div>
            <br>
            <div>
            <button type="button" onclick="basicAlertTest();">Click Me!</button>
            </div>
        </div>

        <script type="text/javascript" charset="utf-8">
            // onSuccess Callback
            // current GPS coordinates
            var onSuccess = function(position) {
                alert('Latitude: '          + position.coords.latitude          + '\n' +
                      'Longitude: '         + position.coords.longitude         + '\n' +
                      'Altitude: '          + position.coords.altitude          + '\n' +
                      'Accuracy: '          + position.coords.accuracy          + '\n' +
                      'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
                      'Heading: '           + position.coords.heading           + '\n' +
                      'Speed: '             + position.coords.speed             + '\n' +
                      'Timestamp: '         + position.timestamp                + '\n');
            };

            // onError Callback receives a PositionError object
            function onError(error) {
                alert('code: '    + error.code    + '\n' +
                      'message: ' + error.message + '\n');
            }

            // Listening for the device to be ready
            document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady() {
                console.log("navigator.geolocation should be able to run successfully now...");
                navigator.geolocation.getCurrentPosition(onSuccess, onError);
            }

            // Checking to see if a basic alert will appear on click of "Click me!" button
            function basicAlertTest(){
            alert("This is the alert test, button works!");
            }
        </script>

        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>

    </body>
</html> 

我缺少什么基本的东西吗?我以为我可以像往常一样用 HTML/Javascript/CSS 编写代码,但需要学习一些代码行来集成使用 native 设备功能(如地理定位或相机)的插件。我已经确保安装了地理定位插件(使用 cordova plugin add cordova-plugin-geolocation ),但没有出现警报。我是否需要单独的插件来显示警报/与屏幕交互?

此外,我注意到每当我对其进行虚拟测试时,如果我查看“扩展控件”中的位置,它给出的坐标是:

Longitude: -122.0840 Latitude: 37.4220 Altitude: 0.0

那是加利福尼亚州山景城,离我大约 8000 英里 ¯_(ツ)_/¯

截图如下:

我正在本地测试这个,这有什么不同吗?我真的很感激任何帮助或建议,我可能遗漏了一些非常明显的东西。提前致谢!

更新 1 从“cordova plugin ls”返回的已安装插件列表:

cordova-plugin-compat 1.0.0 "Compat" cordova-plugin-dialogs 1.3.0 "Notification" cordova-plugin-geolocation 2.4.0 "Geolocation" cordova-plugin-whitelist 1.3.0 "Whitelist"

更新 2

onSuccess功能应该在设备准备就绪后运行。当它运行时,它应该显示包含位置详细信息的警报,但由于我收到的是“设备准备就绪”消息,但没有出现任何警报,我决定添加一个按钮来手动调用该函数。

我现在确定onSuccess设备准备就绪后无法正常运行,因为每当我单击按钮使其手动运行时,控制台中都会显示以下错误:

Uncaught TypeError: Cannot read property 'coords' of undefined

我很困惑,因为我使用的是与此处所示相同的代码:https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-geolocation/index.html

另外,我注意到我正在处理的索引模板包含 <script type="text/javascript" src="cordova.js"></script> ,但是当我查看包含我的索引文件的文件夹时,没有 cordova.js 文件,它不在那里,我似乎无法在 cordova 下载中找到它,这是正常的还是需要下载分开?

最近的尝试:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src * gap://ready file:; style-src 'self' 'unsafe-inline' *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; img-src * data: 'unsafe-inline'">
        <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">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>

        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </head>
    <body>  
        <div class="app">
            <h1 id="headertext">My first Cordova App!</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received" id="geolocation">Device is ready!</p>
            </div>
            <br>
            <div>
            <button type="button" onclick="basicAlertTest();">Click Me!</button>
            <button type="button" onclick="onSuccess();">Run onSuccess function</button>
            </div>
        </div>

        <script type="text/javascript" charset="utf-8">

                   // onSuccess Callback
            // current GPS coordinates
            var onSuccess = function(position) {
                alert('Latitude: '          + position.coords.latitude          + '\n' +
                      'Longitude: '         + position.coords.longitude         + '\n' +
                      'Altitude: '          + position.coords.altitude          + '\n' +
                      'Accuracy: '          + position.coords.accuracy          + '\n' +
                      'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
                      'Heading: '           + position.coords.heading           + '\n' +
                      'Speed: '             + position.coords.speed             + '\n' +
                      'Timestamp: '         + position.timestamp                + '\n');
            };



            // onError Callback receives a PositionError object
            function onError(error) {
                alert('code: '    + error.code    + '\n' +
                      'message: ' + error.message + '\n');
            }

            // Listening for the device to be ready
            document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady() {
                console.log("navigator.geolocation should be able to run successfully now...");
                navigator.geolocation.getCurrentPosition(onSuccess, onError);
            }

            // Checking to see if a basic alert will appear on click of "Click me!" button
            function basicAlertTest(){
            console.log("This is the alert test, button works!");
            alert("This is the alert test, button works!");
            }
        </script>

    </body>
</html>

最佳答案

删除 index.html 文件顶部的这一行

<meta http-equiv="Content-Security-Policy" content="default-src * gap: ws: https://ssl.gstatic.com;style-src * 'unsafe-inline' 'self' data: blob:;script-src * 'unsafe-inline' 'unsafe-eval' data: blob:;img-src * data: 'unsafe-inline' 'self' content:;fmedia-src mediastream;">

关于javascript - 无法与 Cordova 应用程序中的任何内容进行交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40107939/

有关javascript - 无法与 Cordova 应用程序中的任何内容进行交互的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  4. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  5. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  6. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  7. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

随机推荐