ZeroFrame.coffee 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. class ZeroFrame extends Class
  2. constructor: (url) ->
  3. @url = url
  4. @waiting_cb = {}
  5. @wrapper_nonce = document.location.href.replace(/.*wrapper_nonce=([A-Za-z0-9]+).*/, "$1")
  6. @connect()
  7. @next_message_id = 1
  8. @history_state = {}
  9. @init()
  10. init: ->
  11. @
  12. connect: ->
  13. @target = window.parent
  14. window.addEventListener("message", @onMessage, false)
  15. @cmd("innerReady")
  16. # Save scrollTop
  17. window.addEventListener "beforeunload", (e) =>
  18. @log "save scrollTop", window.pageYOffset
  19. @history_state["scrollTop"] = window.pageYOffset
  20. @cmd "wrapperReplaceState", [@history_state, null]
  21. # Restore scrollTop
  22. @cmd "wrapperGetState", [], (state) =>
  23. @history_state = state if state?
  24. @log "restore scrollTop", state, window.pageYOffset
  25. if window.pageYOffset == 0 and state
  26. window.scroll(window.pageXOffset, state.scrollTop)
  27. onMessage: (e) =>
  28. message = e.data
  29. cmd = message.cmd
  30. if cmd == "response"
  31. if @waiting_cb[message.to]?
  32. @waiting_cb[message.to](message.result)
  33. delete @waiting_cb[message.to]
  34. else
  35. @log "Websocket callback not found:", message
  36. else if cmd == "wrapperReady" # Wrapper inited later
  37. @cmd("innerReady")
  38. else if cmd == "ping"
  39. @response message.id, "pong"
  40. else if cmd == "wrapperOpenedWebsocket"
  41. @onOpenWebsocket()
  42. else if cmd == "wrapperClosedWebsocket"
  43. @onCloseWebsocket()
  44. else
  45. @onRequest cmd, message.params
  46. onRequest: (cmd, message) =>
  47. @log "Unknown request", message
  48. response: (to, result) ->
  49. @send {"cmd": "response", "to": to, "result": result}
  50. cmd: (cmd, params={}, cb=null) ->
  51. @send {"cmd": cmd, "params": params}, cb
  52. send: (message, cb=null) ->
  53. message.wrapper_nonce = @wrapper_nonce
  54. message.id = @next_message_id
  55. @next_message_id += 1
  56. @target.postMessage(message, "*")
  57. if cb
  58. @waiting_cb[message.id] = cb
  59. onOpenWebsocket: =>
  60. @log "Websocket open"
  61. onCloseWebsocket: =>
  62. @log "Websocket close"
  63. window.ZeroFrame = ZeroFrame