您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

PostMessageTransportBackend.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import Postis from 'postis';
  2. /**
  3. * The default options for postis.
  4. *
  5. * @type {Object}
  6. */
  7. const DEFAULT_POSTIS_OPTIONS = {
  8. window: window.opener || window.parent
  9. };
  10. /**
  11. * The postis method used for all messages.
  12. *
  13. * @type {string}
  14. */
  15. const POSTIS_METHOD_NAME = 'message';
  16. /**
  17. * Implements message transport using the postMessage API.
  18. */
  19. export default class PostMessageTransportBackend {
  20. /**
  21. * Creates new PostMessageTransportBackend instance.
  22. *
  23. * @param {Object} options - Optional parameters for configuration of the
  24. * transport.
  25. */
  26. constructor({ postisOptions } = {}) {
  27. // eslint-disable-next-line new-cap
  28. this.postis = Postis({
  29. ...DEFAULT_POSTIS_OPTIONS,
  30. ...postisOptions
  31. });
  32. this._receiveCallback = () => {
  33. // Do nothing until a callback is set by the consumer of
  34. // PostMessageTransportBackend via setReceiveCallback.
  35. };
  36. this.postis.listen(
  37. POSTIS_METHOD_NAME,
  38. message => this._receiveCallback(message));
  39. }
  40. /**
  41. * Disposes the allocated resources.
  42. *
  43. * @returns {void}
  44. */
  45. dispose() {
  46. this.postis.destroy();
  47. }
  48. /**
  49. * Sends the passed message.
  50. *
  51. * @param {Object} message - The message to be sent.
  52. * @returns {void}
  53. */
  54. send(message) {
  55. this.postis.send({
  56. method: POSTIS_METHOD_NAME,
  57. params: message
  58. });
  59. }
  60. /**
  61. * Sets the callback for receiving data.
  62. *
  63. * @param {Function} callback - The new callback.
  64. * @returns {void}
  65. */
  66. setReceiveCallback(callback) {
  67. this._receiveCallback = callback;
  68. }
  69. }