首页 > 解决方案 > “未捕获的安全错误:无法从 'Document' 读取 'cookie' 属性:在 'data:' URL 中禁用了 Cookie。” 颤振网页视图

问题描述

WebView(initialUrl:Uri.dataFromString('<script type="text/javascript" src="https://cdn.embedly.com/widgets/platform.js"></script>'+<html>Some code</html>,mimeType: 'text/html').toString(), javascriptMode: JavascriptMode.unrestricted,),

此 CDN 抛出此错误:

未捕获的安全错误:无法从“文档”读取“cookie”属性:cookie 在“数据:”URL 中被禁用。” Flutter webview

标签: javascriptfluttercookieswebview

解决方案


你可以试试我的插件flutter_inappwebview,这是一个 Flutter 插件,允许你添加内联 WebView 或打开应用内浏览器窗口,并且有很多事件、方法和选项来控制 WebView。

在您的情况下,您可以使用参数并通过属性设置initialData自定义 HTML并将其设置为:InAppWebViewInitialData.dataInAppWebViewInitialData.baseUrlhttp://localhost

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String customHTML = "";

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
                initialData: InAppWebViewInitialData(data: """
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>InAppWebViewInitialDataTest</title>
        <script type="text/javascript" src="https://cdn.embedly.com/widgets/platform.js"></script>
    </head>
    <body>
        $customHTML
    </body>
</html>
                    """, baseUrl: 'http://localhost'),
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true,
              )
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop:(InAppWebViewController controller, String url) {

            },
          ))
        ])),
      ),
    );
  }
}

现在您可以document.cookie使用 JavaScript!

另一种方法是将您的 HTML 放入资产文件中(请参阅在资产文件夹中加载文件部分),然后,您可以使用InAppLocalhostServer 启动本地服务器来为您的 HTML 文件提供脚本。


推荐阅读