ext-xdomain-messaging.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Should not be needed for same domain control (just call via child frame),
  3. * but an API common for cross-domain and same domain use can be found
  4. * in embedapi.js with a demo at embedapi.html
  5. */
  6. /*globals svgEditor, svgCanvas*/
  7. svgEditor.addExtension('xdomain-messaging', function() {'use strict';
  8. try {
  9. window.addEventListener('message', function(e) {
  10. // We accept and post strings for the sake of IE9 support
  11. if (typeof e.data !== 'string' || e.data.charAt() === '|') {
  12. return;
  13. }
  14. var cbid, name, args, message, allowedOrigins, data = JSON.parse(e.data);
  15. if (!data || typeof data !== 'object' || data.namespace !== 'svgCanvas') {
  16. return;
  17. }
  18. // The default is not to allow any origins, including even the same domain or if run on a file:// URL
  19. // See config-sample.js for an example of how to configure
  20. allowedOrigins = svgEditor.curConfig.allowedOrigins;
  21. if (allowedOrigins.indexOf('*') === -1 && allowedOrigins.indexOf(e.origin) === -1) {
  22. return;
  23. }
  24. cbid = data.id;
  25. name = data.name;
  26. args = data.args;
  27. message = {
  28. namespace: 'svg-edit',
  29. id: cbid
  30. };
  31. try {
  32. message.result = svgCanvas[name].apply(svgCanvas, args);
  33. } catch (err) {
  34. message.error = err.message;
  35. }
  36. e.source.postMessage(JSON.stringify(message), '*');
  37. }, false);
  38. }
  39. catch (err) {
  40. console.log('Error with xdomain message listener: ' + err);
  41. }
  42. });