You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android WebView嵌入HTML页面JS无法执行问题求助

Xamarin.Forms Android WebView JavaScript 不执行问题解决方法

你的问题核心是Xamarin.Forms WebView默认禁用JavaScript,加上本地资源引用路径的小问题,按以下步骤修改即可解决:


1. 启用WebView的JavaScript支持

Xamarin.Forms的WebView默认关闭JS执行,必须手动开启。你可以直接在XAML中设置属性:

修改MainPage.xaml中的WebView节点:

<WebView x:Name="webView" WidthRequest="1000" HeightRequest="1000" IsJavaScriptEnabled="True" />

或者在后台代码中添加设置:

public MainPage()
{
    InitializeComponent();
    webView.IsJavaScriptEnabled = true; // 新增这行开启JS支持
    webView.Source = "file:///android_asset/titi.html";
}

2. 修正本地JS文件的引用路径

你的titi.html中引用titi.js的路径是./titi.js,在Android Assets目录下,直接使用文件名即可,修改为:

<script src="titi.js"></script>

3. 可选:避免jQuery网络加载失败问题

如果设备处于无网络环境,远程加载的jQuery会失败,导致依赖jQuery的代码无法运行。建议下载jquery-2.1.4.min.js到Assets目录,改为本地引用:

<script src="jquery-2.1.4.min.js"></script>

修改后的完整代码示例

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" IsJavaScriptEnabled="True" />
    </StackLayout>

</ContentPage>

titi.html

<html>
    <body>
        <!-- 改为本地引用jQuery,避免网络依赖 -->
        <script src="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="displayName($('#name').val());">Test Button</button>
        <br />
        <p id="result">Result:</p>
        <script src="titi.js"></script>
    
    </body>
</html>

内容的提问来源于stack exchange,提问作者Lemec Cinq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:33:28