hotent.helper.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * !Copyright (c) 2021 Hotent(http://www.hotent.com)
  3. *
  4. * Version: 1.0.0
  5. */
  6. ;(function () {
  7. var hotent = {
  8. alreadyGetHeight: false,
  9. }
  10. window.hotent = hotent
  11. setTimeout(function () {
  12. // 如果url表单未传递高度消息时,会默认在300ms后传递
  13. if (!hotent.alreadyGetHeight) {
  14. hotent.getHeight()
  15. }
  16. }, 300)
  17. // 是否现代浏览器
  18. hotent.isModern = function () {
  19. return window.addEventListener ? true : false
  20. }
  21. // 获取url参数
  22. hotent.getUrlParam = function (key) {
  23. var query = window.location.search.substring(1)
  24. var vars = query.split('&')
  25. for (var i = 0; i < vars.length; i++) {
  26. var pair = vars[i].split('=')
  27. if (pair[0] == key) {
  28. return pair[1]
  29. }
  30. }
  31. return false
  32. }
  33. // 添加事件监听
  34. hotent.addListener = function (name, fn) {
  35. if (!name || name.constructor != String) {
  36. throw 'name could not be empty and must be String.'
  37. }
  38. if (!fn || fn.constructor != Function) {
  39. throw 'fn could not be empty and must be Function.'
  40. }
  41. var eventMethod = hotent.isModern ? 'addEventListener' : 'attachEvent',
  42. eventer = window[eventMethod]
  43. var match = name.match(/^on(\w+)$/)
  44. if (match && match.length == 2) {
  45. name = match[1]
  46. }
  47. eventer(hotent.isModern ? name : 'on' + name, fn)
  48. }
  49. // 发送消息给父页面
  50. hotent.sendMessage = function (params) {
  51. window.parent && window.parent.postMessage(params, '*')
  52. }
  53. // 监听父页面发送过来的message
  54. hotent.addListener('message', function (e) {
  55. var type = e.data || 0
  56. if (!type || type.type != 'roger') {
  57. // 子页面先回复父页面:收到消息
  58. hotent.sendMessage({ type: 'roger' })
  59. }
  60. switch (type) {
  61. case 'getHeight' /*获取页面高度*/:
  62. hotent.getHeight()
  63. break
  64. case 'saveData': /*保存页面数据*/
  65. case 'modifyForm': /*打开新页面编辑数据*/
  66. case 'printForm': /*打印*/
  67. case 'validForm' /*验证数据*/:
  68. hotent.invoke(type)
  69. break
  70. }
  71. })
  72. // 调用页面定义的方法
  73. hotent.invoke = function (methodName) {
  74. var r = window[methodName]
  75. if (!r || r.constructor != Function) {
  76. throw '页面未提供方法:' + methodName
  77. } else {
  78. r.apply()
  79. }
  80. }
  81. // 获取页面高度
  82. hotent.getHeight = function () {
  83. var height = document.getElementsByTagName('body')[0].scrollHeight,
  84. params = { type: 'height', height: height }
  85. hotent.sendMessage(params)
  86. hotent.alreadyGetHeight = true
  87. }
  88. // 监听鼠标滚动事件
  89. hotent.addListener('wheel', function (e) {
  90. var params = { type: 'wheel', wheelDeltaY: -e.deltaY }
  91. hotent.sendMessage(params)
  92. })
  93. })()