| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package nativehost
- import (
- "encoding/json"
- "clusterflow.dev/cfbrowser/api"
- )
- // CDPCall uses WebView2's native COM channel, never a remote debugging port.
- type CDPCall func(method string, params json.RawMessage, done func(json.RawMessage, error))
- func CDPEvaluate(call CDPCall, expression string, done func(json.RawMessage, error)) {
- call("Page.getFrameTree", json.RawMessage(`{}`), func(raw json.RawMessage, err error) {
- var tree struct {
- FrameTree struct {
- Frame struct {
- ID string `json:"id"`
- } `json:"frame"`
- } `json:"frameTree"`
- }
- if err != nil {
- done(nil, err)
- return
- }
- if json.Unmarshal(raw, &tree) != nil || tree.FrameTree.Frame.ID == "" {
- done(nil, api.Err("BROWSER_INVALID_RESULT", "WebView2 main frame is unavailable"))
- return
- }
- params, _ := json.Marshal(map[string]any{"frameId": tree.FrameTree.Frame.ID, "worldName": "cfbrowser-isolated"})
- call("Page.createIsolatedWorld", params, func(raw json.RawMessage, err error) {
- var world struct {
- ID int64 `json:"executionContextId"`
- }
- if err != nil {
- done(nil, err)
- return
- }
- if json.Unmarshal(raw, &world) != nil || world.ID <= 0 {
- done(nil, api.Err("BROWSER_INVALID_RESULT", "WebView2 isolated world is unavailable"))
- return
- }
- params, _ = json.Marshal(map[string]any{"expression": expression, "contextId": world.ID, "returnByValue": true})
- call("Runtime.evaluate", params, func(raw json.RawMessage, err error) {
- if err != nil {
- done(nil, err)
- return
- }
- var response struct {
- Result struct {
- Value json.RawMessage `json:"value"`
- } `json:"result"`
- Exception json.RawMessage `json:"exceptionDetails"`
- }
- if json.Unmarshal(raw, &response) != nil || len(response.Exception) > 0 && string(response.Exception) != "null" {
- done(nil, api.Err("BROWSER_SCRIPT_FAILED", "WebView2 page evaluation failed"))
- return
- }
- if len(response.Result.Value) == 0 {
- done(nil, api.Err("BROWSER_INVALID_RESULT", "WebView2 evaluation returned no JSON value"))
- return
- }
- done(response.Result.Value, nil)
- })
- })
- })
- }
|