Java Swing 嵌入微软 WebView2 的运行环境设置

Java Swing 嵌入微软 WebView2 的运行环境设置


目标

当使用 DJNativeSwingEclipse swt 开发 Windows 桌面 Java 应用时,因为使用 Javascript 动态载入 html 片段, 导致 CORS 异常.

Access to XMLHttpRequest at ‘file:///…’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome-untrusted, https, edge.

这里提供一种对用户透明的解决方案。

主机

系统:

  1. Windows 11 专业版 22H2
  2. Microsoft WebView2 已经安装

开发环境: IntelliJ IDEA 2022.3 (Ultimate Edition)

参考资料

1. DJNativeSwing

2. Eclipse swt

原理

参考文件 DJ-Native-Swing\swt-4.26RC2-win32-win32-x86_64\src\org\eclipse\swt\browser\Edge.java

// System.getProperty() keys
static final String BROWSER_DIR_PROP = "org.eclipse.swt.browser.EdgeDir";
static final String BROWSER_ARGS_PROP = "org.eclipse.swt.browser.EdgeArgs";
static final String DATA_DIR_PROP = "org.eclipse.swt.browser.EdgeDataDir";
static final String LANGUAGE_PROP = "org.eclipse.swt.browser.EdgeLanguage";
static final String VERSIONT_PROP = "org.eclipse.swt.browser.EdgeVersion";

BROWSER_ARGS_PROP 即为 ICoreWebView2EnvironmentOptions 可选参数 ‘value’,更详细的可以参考 Chromium 的启动参数,目前 MS Edge 与其保持一致。

微软的官方说明,注意参数格式

public HRESULT put_AdditionalBrowserArguments(LPCWSTR value)

Please note that calling this API twice will replace the previous value rather than appending to it. If there are multiple switches, there should be a space in between them. The one exception is if multiple features are being enabled/disabled for a single switch, in which case the features should be comma-seperated. Ex. "--disable-features=feature1,feature2 --some-other-switch --do-something"

2022-12-14 疫情正当前,值得纪念


版权声明:本文为kelvinchn原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。