Xamarin:嵌入WebView的html页面不执行js

r7xajy2e  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(217)

我有一个新的Android Xamarin解决方案。我想在WebView中嵌入一个执行js脚本的HTML页面。我在Android资产中添加了这个html和这个js页面。

MainPage.xaml
    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.MainPage">

    <StackLayout>
        <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
            <Label Text="Welcome to Xamarin.Forms!" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
        </Frame>
        <Label Text="Start developing now" FontSize="Title" Padding="30,10,30,10"/>
        <Label Text="Make changes to your XAML file and save to see your UI update in the running app with XAML Hot Reload. Give it a try!" FontSize="16" Padding="30,0,30,0"/>
        <Label FontSize="16" Padding="30,24,30,0">
            <Label.FormattedText>
                <FormattedString>
                    <FormattedString.Spans>
                        <Span Text="Learn more at "/>
                        <Span Text="https://aka.ms/xamarin-quickstart" FontAttributes="Bold"/>
                    </FormattedString.Spans>
                </FormattedString>
            </Label.FormattedText>
        </Label>
        <WebView x:Name="webView" WidthRequest="1000" HeightRequest="1000" />
    </StackLayout>

</ContentPage>

MainPage.xaml.cs

using Xamarin.Forms;
    
    namespace App1
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
    
                webView.Source = "file:///android_asset/titi.html";
            }
        }
    }

titi.html

<html>
    <body>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    
        <h1>Webview Test</h1>
        <br />
        Enter name: <input type="text" id="name">
        <br />
        <br />
        <button type="button" onclick="javascript: displayName($('#name').val());">Test Button</button>
        <br />
        <p id="result">Result:</p>
        <script src="./titi.js"></script>
    
    </body>
    </html>

titi.js

function displayName(str) {
    try {
        $('#result').text($('#result').text() + " " + str);
    
    }
    catch (err) {
        log(err);
    }
}

当我点击按钮时,HTML页面正确显示,但js部分未执行。
你能帮我疏通一下吗?

polkgigr

polkgigr1#

如果我不在js文件中使用jquery,它就可以工作。

function displayName(str) {
     var result = document.querySelector('#result');
     result.innerHTML = str;
  }

相关问题