cdp.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package nativehost
  2. import (
  3. "encoding/json"
  4. "clusterflow.dev/cfbrowser/api"
  5. )
  6. // CDPCall uses WebView2's native COM channel, never a remote debugging port.
  7. type CDPCall func(method string, params json.RawMessage, done func(json.RawMessage, error))
  8. func CDPEvaluate(call CDPCall, expression string, done func(json.RawMessage, error)) {
  9. call("Page.getFrameTree", json.RawMessage(`{}`), func(raw json.RawMessage, err error) {
  10. var tree struct {
  11. FrameTree struct {
  12. Frame struct {
  13. ID string `json:"id"`
  14. } `json:"frame"`
  15. } `json:"frameTree"`
  16. }
  17. if err != nil {
  18. done(nil, err)
  19. return
  20. }
  21. if json.Unmarshal(raw, &tree) != nil || tree.FrameTree.Frame.ID == "" {
  22. done(nil, api.Err("BROWSER_INVALID_RESULT", "WebView2 main frame is unavailable"))
  23. return
  24. }
  25. params, _ := json.Marshal(map[string]any{"frameId": tree.FrameTree.Frame.ID, "worldName": "cfbrowser-isolated"})
  26. call("Page.createIsolatedWorld", params, func(raw json.RawMessage, err error) {
  27. var world struct {
  28. ID int64 `json:"executionContextId"`
  29. }
  30. if err != nil {
  31. done(nil, err)
  32. return
  33. }
  34. if json.Unmarshal(raw, &world) != nil || world.ID <= 0 {
  35. done(nil, api.Err("BROWSER_INVALID_RESULT", "WebView2 isolated world is unavailable"))
  36. return
  37. }
  38. params, _ = json.Marshal(map[string]any{"expression": expression, "contextId": world.ID, "returnByValue": true})
  39. call("Runtime.evaluate", params, func(raw json.RawMessage, err error) {
  40. if err != nil {
  41. done(nil, err)
  42. return
  43. }
  44. var response struct {
  45. Result struct {
  46. Value json.RawMessage `json:"value"`
  47. } `json:"result"`
  48. Exception json.RawMessage `json:"exceptionDetails"`
  49. }
  50. if json.Unmarshal(raw, &response) != nil || len(response.Exception) > 0 && string(response.Exception) != "null" {
  51. done(nil, api.Err("BROWSER_SCRIPT_FAILED", "WebView2 page evaluation failed"))
  52. return
  53. }
  54. if len(response.Result.Value) == 0 {
  55. done(nil, api.Err("BROWSER_INVALID_RESULT", "WebView2 evaluation returned no JSON value"))
  56. return
  57. }
  58. done(response.Result.Value, nil)
  59. })
  60. })
  61. })
  62. }