背景
在瀏覽器中訪問本地靜態(tài)資源html網(wǎng)頁(yè)時(shí),可能會(huì)遇到跨域問題如圖。
?
是因?yàn)闉g覽器默認(rèn)啟用了同源策略,即只允許加載與當(dāng)前網(wǎng)頁(yè)具有相同源(協(xié)議、域名和端口)的內(nèi)容。
WebView2默認(rèn)情況下啟用了瀏覽器的同源策略,即只允許加載與主機(jī)相同源的內(nèi)容。所以如果我們把靜態(tài)資源發(fā)布到iis或者通過node進(jìn)行啟動(dòng)就可以看到不跨域了。
解決方案
-
使用CORS(Cross-Origin Resource Sharing):如果你有控制服務(wù)器端,可以在服務(wù)器端配置CORS來允許跨域請(qǐng)求。在服務(wù)器端的響應(yīng)頭中添加相關(guān)的CORS頭部信息,例如允許訪問的域名、請(qǐng)求方法等,以允許JavaScript跨域訪問。
- 使用WebView2的
AddWebResourceRequestedFilter
方法:通過添加Web資源請(qǐng)求過濾器,你可以攔截WebView2控件中加載的資源請(qǐng)求,并進(jìn)行處理。在攔截到JavaScript文件請(qǐng)求時(shí),修改響應(yīng)頭部信息,添加Access-Control-Allow-Origin
頭部來解決跨域問題。 - 使用代理服務(wù)器:你可以在本地啟動(dòng)一個(gè)代理服務(wù)器,將WebView2控件的請(qǐng)求轉(zhuǎn)發(fā)到代理服務(wù)器上,然后代理服務(wù)器再將請(qǐng)求發(fā)送到原始服務(wù)器并返回響應(yīng)。在代理服務(wù)器上你可以設(shè)置合適的CORS頭部信息來解決跨域問題。
思路
-
首先,確保你已經(jīng)安裝了
Microsoft.Web.WebView2
。你可以在Visual Studio的NuGet包管理器中搜索并安裝此包。 - 然后通過HttpListener進(jìn)行文件夾的靜態(tài)資源進(jìn)行代理發(fā)布
- 然后通過webview2進(jìn)行導(dǎo)航訪問即可我們會(huì)發(fā)現(xiàn)跨域問題已經(jīng)解決
?
代碼
?
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinApp.View { public partial class Cors : Form { // 創(chuàng)建HttpListener對(duì)象并指定綁定的端口 HttpListener _listener; string _folderPath; string _rootDirectory; public Cors() { InitializeComponent(); // 初始化 InitializeAsync(); } private async void InitializeAsync() { // 獲取本地靜態(tài)資源的路徑 _rootDirectory = AppDomain.CurrentDomain.BaseDirectory + "offline-exam-player"; //設(shè)置本地離線播放器為代理服務(wù) _rootDirectory = @"C:\Users\admin\Documents\WeChat Files\wxid_1ofgk575ybpt22\FileStorage\File\2024-02\ng-alain8\ng-alain8/"; _folderPath = @"C:\Users\admin\Documents\WeChat Files\wxid_1ofgk575ybpt22\FileStorage\File\2024-02\ng-alain8\ng-alain8/index.html"; _listener = new HttpListener(); // 設(shè)置代理服務(wù)器的監(jiān)聽地址和端口號(hào) _listener.Prefixes.Add("http://localhost:8080/"); _listener.Start(); // 啟動(dòng)代理服務(wù)器 Task.Run(() => { // 啟動(dòng)代理服務(wù)器 ProcessRequests(); }); // 停止代理服務(wù)器(這里演示就不停止了) //server.Stop(); } private void ProcessRequests() { try { while (_listener.IsListening) { HttpListenerContext context = _listener.GetContext(); string requestPath = context.Request.Url.AbsolutePath; string filePath = _rootDirectory + requestPath; // Serve the requested file if it exists if (System.IO.File.Exists(filePath)) { string extension = System.IO.Path.GetExtension(filePath); string contentType; switch (extension) { case ".html": contentType = "text/html"; break; case ".js": contentType = "application/javascript"; break; case ".less": case ".css": contentType = "text/css"; break; case ".svg": contentType = "image/svg+xml"; break; default: contentType = "application/octet-stream"; break; } context.Response.ContentType = contentType; //context.Response.ContentType = "text/html"; byte[] responseBuffer = System.IO.File.ReadAllBytes(filePath); context.Response.OutputStream.Write(responseBuffer, 0, responseBuffer.Length); context.Response.Close(); } else { // Return a 404 response if the file does not exist context.Response.StatusCode = 404; context.Response.Close(); } } } catch (Exception ex) { // Handle any exceptions that may occur Console.WriteLine(ex.ToString()); } } private async void Cors_Load(object sender, EventArgs e) { //本地靜態(tài)資源,直接訪問會(huì)出現(xiàn)跨院,如果通過iis訪問則不會(huì)跨域; // 確保CoreWebView2運(yùn)行時(shí)已準(zhǔn)備就緒 await webView21.EnsureCoreWebView2Async(); // 在WebView2控件中加載URL //webView21.CoreWebView2.Navigate(_folderPath); webView21.CoreWebView2.Navigate("http://localhost:8080/" + "index.html"); } } }
?文章來源:http://www.zghlxwxcb.cn/news/detail-830549.html
結(jié)語(yǔ)
最后如果對(duì)于不多的跨域js文件,可以把js的代碼內(nèi)嵌到index.html頁(yè)面實(shí)現(xiàn)。就是<script>跨域js內(nèi)容</script>文章來源地址http://www.zghlxwxcb.cn/news/detail-830549.html
到了這里,關(guān)于c#使用webView2 訪問本地靜態(tài)html資源跨域Cors問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!