python-3.xwxpythontauri

How does wxpython html2 load dist index.html while keeping js css running normally?


This dist is generated by Vue

enter image description here

import os
import wx
import wx.html2


class MyBrowser(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        web_path = os.path.join(os.getcwd(), 'static', 'dist', 'index.html')
        self.url = f"file:///{web_path}"
      
        self.browser = wx.html2.WebView.New(self)

        self.browser.LoadURL(self.url)

    def on_open(self, event):
        self.browser.LoadURL(self.url)


if __name__ == '__main__':
    app = wx.App(False)
    frame = MyBrowser(None, wx.ID_ANY, "My Local Web App")
    frame.Show()
    app.MainLoop()

I had to do this because I was trying to mimic tauri wry's way of loading index.html


Solution

  • This can be achieved using wx.html2.WebViewHandler custom protocol

    class AppSchemeHandler(wx.html2.WebViewHandler):
        def __init__(self, base_path: str):
            super(AppSchemeHandler, self).__init__("app")
            self.base_path = base_path
            logging.basicConfig(level=logging.DEBUG)
    
        def GetFile(self, uri: str) -> FSFile | None:
            _, path = uri.split("://", 1)
            print(path, 'sssss')
            actual_path = os.path.join(self.base_path, os.path.normpath(path.lstrip('/')))
            logging.debug(f"解析路径: {actual_path}")
            # 如果路径指向一个目录,则自动尝试定位到 index.html
            if os.path.isdir(actual_path):
                actual_path = os.path.join(actual_path, 'index.html')
    
            try:
                # 读取文件内容
                with open(actual_path, "rb") as file:
                    stream = BytesIO(file.read())
                    # 获取 MIME 类型
                    mime_type, _ = mimetypes.guess_type(actual_path)
                    # 创建 wx.FSFile 对象
                    fsfile = wx.FSFile(stream, uri, mime_type, "", wx.DateTime.Now())
                    return fsfile
            except FileNotFoundError:
                logging.error(f"文件未找到: {actual_path}")
            except Exception as e:
                logging.error(f"读取文件错误 {actual_path}: {e}")
            return None