ZeroFrame.coffee 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. else
  34. @log "Websocket callback not found:", message
  35. else if cmd == "wrapperReady" # Wrapper inited later
  36. @cmd("innerReady")
  37. else if cmd == "ping"
  38. @response message.id, "pong"
  39. else if cmd == "wrapperOpenedWebsocket"
  40. @onOpenWebsocket()
  41. else if cmd == "wrapperClosedWebsocket"
  42. @onCloseWebsocket()
  43. else
  44. @onRequest cmd, message.params
  45. onRequest: (cmd, message) =>
  46. @log "Unknown request", message
  47. response: (to, result) ->
  48. @send {"cmd": "response", "to": to, "result": result}
  49. cmd: (cmd, params={}, cb=null) ->
  50. @send {"cmd": cmd, "params": params}, cb
  51. send: (message, cb=null) ->
  52. message.wrapper_nonce = @wrapper_nonce
  53. message.id = @next_message_id
  54. @next_message_id += 1
  55. @target.postMessage(message, "*")
  56. if cb
  57. @waiting_cb[message.id] = cb
  58. onOpenWebsocket: =>
  59. @log "Websocket open"
  60. onCloseWebsocket: =>
  61. @log "Websocket close"
  62. window.ZeroFrame = ZeroFrame