api.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. /*!
  2. * Copyright (c) Ascensio System SIA 2022. All rights reserved
  3. *
  4. * http://www.onlyoffice.com
  5. *
  6. * Version: 7.1.1 (build:23)
  7. */
  8. ;(function(DocsAPI, window, document, undefined) {
  9. /*
  10. # Full #
  11. config = {
  12. type: 'desktop or mobile or embedded',
  13. width: '100% by default',
  14. height: '100% by default',
  15. documentType: 'word' | 'cell' | 'slide',// deprecate 'text' | 'spreadsheet' | 'presentation',
  16. token: <string> encrypted signature
  17. document: {
  18. title: 'document title',
  19. url: 'document url'
  20. fileType: 'document file type',
  21. options: <advanced options>,
  22. key: 'key',
  23. vkey: 'vkey',
  24. info: {
  25. owner: 'owner name',
  26. folder: 'path to document',
  27. uploaded: '<uploaded date>',
  28. sharingSettings: [
  29. {
  30. user: 'user name',
  31. permissions: '<permissions>',
  32. isLink: false
  33. },
  34. ...
  35. ],
  36. favorite: '<file is favorite>' // true/false/undefined (undefined - don't show fav. button)
  37. },
  38. permissions: {
  39. edit: <can edit>, // default = true
  40. download: <can download>, // default = true
  41. reader: <can view in readable mode>,
  42. review: <can review>, // default = edit
  43. print: <can print>, // default = true
  44. comment: <can comment in view mode> // default = edit,
  45. modifyFilter: <can add, remove and save filter in the spreadsheet> // default = true
  46. modifyContentControl: <can modify content controls in documenteditor> // default = true
  47. fillForms: <can edit forms in view mode> // default = edit || review,
  48. copy: <can copy data> // default = true,
  49. editCommentAuthorOnly: <can edit your own comments only> // default = false
  50. deleteCommentAuthorOnly: <can delete your own comments only> // default = false,
  51. reviewGroups: ["Group1", ""] // current user can accept/reject review changes made by users from Group1 and users without a group. [] - use groups, but can't change any group's changes
  52. commentGroups: { // {} - use groups, but can't view/edit/delete any group's comments
  53. view: ["Group1", ""] // current user can view comments made by users from Group1 and users without a group.
  54. edit: ["Group1", ""] // current user can edit comments made by users from Group1 and users without a group.
  55. remove: ["Group1", ""] // current user can remove comments made by users from Group1 and users without a group.
  56. },
  57. userInfoGroups: ["Group1", ""], // show tooltips/cursors/info in header only for users in userInfoGroups groups. [""] - means users without group, [] - don't show any users, null/undefined/"" - show all users
  58. protect: <can protect document> // default = true. show/hide protect tab or protect buttons
  59. }
  60. },
  61. editorConfig: {
  62. actionLink: { // open file and scroll to data, used with onMakeActionLink or the onRequestSendNotify event
  63. action: {
  64. type: "bookmark", // or type="comment"
  65. data: <bookmark name> // or comment id
  66. }
  67. },
  68. mode: 'view or edit',
  69. lang: <language code>,
  70. location: <location>,
  71. canCoAuthoring: <can coauthoring documents>,
  72. canBackToFolder: <can return to folder> - deprecated. use "customization.goback" parameter,
  73. createUrl: 'create document url',
  74. sharingSettingsUrl: 'document sharing settings url',
  75. fileChoiceUrl: 'source url', // for mail merge or image from storage
  76. callbackUrl: <url for connection between sdk and portal>,
  77. mergeFolderUrl: 'folder for saving merged file', // must be deprecated, use saveAsUrl instead
  78. saveAsUrl: 'folder for saving files'
  79. licenseUrl: <url for license>,
  80. customerId: <customer id>,
  81. region: <regional settings> // can be 'en-us' or lang code
  82. user: {
  83. id: 'user id',
  84. name: 'user name',
  85. group: 'group name' // for customization.reviewPermissions or permissions.reviewGroups or permissions.commentGroups. Can be multiple groups separated by commas (,) : 'Group1' or 'Group1,Group2'
  86. },
  87. recent: [
  88. {
  89. title: 'document title',
  90. url: 'document url',
  91. folder: 'path to document',
  92. },
  93. ...
  94. ],
  95. templates: [
  96. {
  97. title: 'template name', // name - is deprecated
  98. image: 'template icon url',
  99. url: 'http://...'
  100. },
  101. ...
  102. ],
  103. customization: {
  104. logo: {
  105. image: url,
  106. imageDark: url, // logo for dark theme
  107. imageEmbedded: url, // deprecated, use image instead
  108. url: http://...
  109. },
  110. customer: {
  111. name: 'SuperPuper',
  112. address: 'New-York, 125f-25',
  113. mail: 'support@gmail.com',
  114. www: 'www.superpuper.com',
  115. info: 'Some info',
  116. logo: '',
  117. logoDark: '', // logo for dark theme
  118. },
  119. about: true,
  120. feedback: {
  121. visible: false,
  122. url: http://...
  123. },
  124. goback: {
  125. url: 'http://...',
  126. text: 'Go to London',
  127. blank: true,
  128. requestClose: false // if true - goback send onRequestClose event instead opening url
  129. },
  130. reviewPermissions: {
  131. "Group1": ["Group2"], // users from Group1 can accept/reject review changes made by users from Group2
  132. "Group2": ["Group1", "Group2"] // users from Group2 can accept/reject review changes made by users from Group1 and Group2
  133. "Group3": [""] // users from Group3 can accept/reject review changes made by users without a group
  134. },
  135. anonymous: { // set name for anonymous user
  136. request: bool (default: true), // enable set name
  137. label: string (default: "Guest") // postfix for user name
  138. },
  139. review: {
  140. hideReviewDisplay: false, // hide button Review mode
  141. hoverMode: false, // true - show review balloons on mouse move, not on click on text
  142. showReviewChanges: false,
  143. reviewDisplay: 'original', // original for viewer, markup for editor
  144. trackChanges: undefined // true/false - open editor with track changes mode on/off,
  145. },
  146. layout: { // hide elements, but don't disable feature
  147. toolbar: {
  148. file: { // menu file
  149. close: false / true, // close menu button
  150. settings: false / true, // advanced settings
  151. info: false / true // document info
  152. save: false/true // save button
  153. } / false / true,
  154. home: {
  155. mailmerge: false/true // mail merge button
  156. },
  157. layout: false / true, // layout tab
  158. references: false / true, // de references tab
  159. collaboration: false / true // collaboration tab
  160. protect: false / true, // protect tab
  161. plugins: false / true // plugins tab
  162. view: {
  163. navigation: false/true // navigation button in de
  164. } / false / true, // view tab
  165. save: false/true // save button on toolbar in
  166. } / false / true, // use instead of customization.toolbar,
  167. header: {
  168. users: false/true // users list button
  169. save: false/true // save button
  170. },
  171. leftMenu: {
  172. navigation: false/true,
  173. spellcheck: false/true // spellcheck button in sse
  174. } / false / true, // use instead of customization.leftMenu
  175. rightMenu: false/true, // use instead of customization.rightMenu
  176. statusBar: {
  177. textLang: false/true // text language button in de/pe
  178. docLang: false/true // document language button in de/pe
  179. actionStatus: false/true // status of operation
  180. } / false / true, // use instead of customization.statusBar
  181. },
  182. features: { // disable feature
  183. spellcheck: {
  184. mode: false/true // init value in de/pe
  185. change: false/true // hide/show feature in de/pe/sse
  186. } / false / true // if false/true - use as init value in de/pe. use instead of customization.spellcheck parameter
  187. },
  188. chat: true,
  189. comments: true,
  190. zoom: 100,
  191. compactToolbar: false,
  192. leftMenu: true, // must be deprecated. use layout.leftMenu instead
  193. rightMenu: true, // must be deprecated. use layout.rightMenu instead
  194. hideRightMenu: false, // hide or show right panel on first loading
  195. toolbar: true, // must be deprecated. use layout.toolbar instead
  196. statusBar: true, // must be deprecated. use layout.statusBar instead
  197. autosave: true,
  198. forcesave: false,
  199. commentAuthorOnly: false, // must be deprecated. use permissions.editCommentAuthorOnly and permissions.deleteCommentAuthorOnly instead
  200. showReviewChanges: false, // must be deprecated. use customization.review.showReviewChanges instead
  201. help: true,
  202. compactHeader: false,
  203. toolbarNoTabs: false,
  204. toolbarHideFileName: false,
  205. reviewDisplay: 'original', // must be deprecated. use customization.review.reviewDisplay instead
  206. spellcheck: true, // must be deprecated. use customization.features.spellcheck instead
  207. compatibleFeatures: false,
  208. unit: 'cm' // cm, pt, inch,
  209. mentionShare : true // customize tooltip for mention,
  210. macros: true // can run macros in document
  211. plugins: true // can run plugins in document
  212. macrosMode: 'warn' // warn about automatic macros, 'enable', 'disable', 'warn',
  213. trackChanges: undefined // true/false - open editor with track changes mode on/off, // must be deprecated. use customization.review.trackChanges instead
  214. hideRulers: false // hide or show rulers on first loading (presentation or document editor)
  215. hideNotes: false // hide or show notes panel on first loading (presentation editor)
  216. uiTheme: 'theme-dark' // set interface theme: id or default-dark/default-light
  217. },
  218. coEditing: {
  219. mode: 'fast', // <coauthoring mode>, 'fast' or 'strict'. if 'fast' and 'customization.autosave'=false -> set 'customization.autosave'=true
  220. change: true, // can change co-authoring mode
  221. },
  222. plugins: {
  223. autostart: ['asc.{FFE1F462-1EA2-4391-990D-4CC84940B754}'],
  224. pluginsData: [
  225. "helloworld/config.json",
  226. "chess/config.json",
  227. "speech/config.json",
  228. "clipart/config.json",
  229. ]
  230. },
  231. wopi: { // only for wopi
  232. FileNameMaxLength: 250 // max filename length for rename, 250 by default
  233. }
  234. },
  235. events: {
  236. 'onAppReady': <application ready callback>,
  237. 'onDocumentStateChange': <document state changed callback>
  238. 'onDocumentReady': <document ready callback>
  239. 'onRequestEditRights': <request rights for switching from view to edit>,
  240. 'onRequestHistory': <request version history>,// must call refreshHistory method
  241. 'onRequestHistoryData': <request version data>,// must call setHistoryData method
  242. 'onRequestRestore': <try to restore selected version>,
  243. 'onRequestHistoryClose': <request closing history>,
  244. 'onError': <error callback>,
  245. 'onWarning': <warning callback>,
  246. 'onInfo': <document open callback>,// send view or edit mode
  247. 'onOutdatedVersion': <outdated version callback>,// send when previous version is opened
  248. 'onDownloadAs': <download as callback>,// send url of downloaded file as a response for downloadAs method
  249. 'onRequestSaveAs': <try to save copy of the document>,
  250. 'onCollaborativeChanges': <co-editing changes callback>,// send when other user co-edit document
  251. 'onRequestRename': <try to rename document>,
  252. 'onMetaChange': // send when meta information changed
  253. 'onRequestClose': <request close editor>,
  254. 'onMakeActionLink': <request link to document with bookmark, comment...>,// must call setActionLink method
  255. 'onRequestUsers': <request users list for mentions>,// must call setUsers method
  256. 'onRequestSendNotify': //send when user is mentioned in a comment,
  257. 'onRequestInsertImage': <try to insert image>,// must call insertImage method
  258. 'onRequestCompareFile': <request file to compare>,// must call setRevisedFile method
  259. 'onRequestSharingSettings': <request sharing settings>,// must call setSharingSettings method
  260. 'onRequestCreateNew': <try to create document>,
  261. }
  262. }
  263. # Embedded #
  264. config = {
  265. type: 'embedded',
  266. width: '100% by default',
  267. height: '100% by default',
  268. documentType: 'word' | 'cell' | 'slide',// deprecate 'text' | 'spreadsheet' | 'presentation',
  269. document: {
  270. title: 'document title',
  271. url: 'document url',
  272. fileType: 'document file type',
  273. key: 'key',
  274. vkey: 'vkey'
  275. },
  276. editorConfig: {
  277. licenseUrl: <url for license>,
  278. customerId: <customer id>,
  279. autostart: 'document', // action for app's autostart. for presentations default value is 'player'
  280. embedded: {
  281. embedUrl: 'url',
  282. fullscreenUrl: 'url',
  283. saveUrl: 'url',
  284. shareUrl: 'url',
  285. toolbarDocked: 'top or bottom'
  286. }
  287. },
  288. events: {
  289. 'onAppReady': <application ready callback>,
  290. 'onBack': <back to folder callback>,
  291. 'onError': <error callback>,
  292. 'onDocumentReady': <document ready callback>,
  293. 'onWarning': <warning callback>
  294. }
  295. }
  296. */
  297. // TODO: allow several instances on one page simultaneously
  298. DocsAPI.DocEditor = function(placeholderId, config) {
  299. var _self = this,
  300. _config = config || {};
  301. extend(_config, DocsAPI.DocEditor.defaultConfig);
  302. _config.editorConfig.canUseHistory = _config.events && !!_config.events.onRequestHistory;
  303. _config.editorConfig.canHistoryClose = _config.events && !!_config.events.onRequestHistoryClose;
  304. _config.editorConfig.canHistoryRestore = _config.events && !!_config.events.onRequestRestore;
  305. _config.editorConfig.canSendEmailAddresses = _config.events && !!_config.events.onRequestEmailAddresses;
  306. _config.editorConfig.canRequestEditRights = _config.events && !!_config.events.onRequestEditRights;
  307. _config.editorConfig.canRequestClose = _config.events && !!_config.events.onRequestClose;
  308. _config.editorConfig.canRename = _config.events && !!_config.events.onRequestRename;
  309. _config.editorConfig.canMakeActionLink = _config.events && !!_config.events.onMakeActionLink;
  310. _config.editorConfig.canRequestUsers = _config.events && !!_config.events.onRequestUsers;
  311. _config.editorConfig.canRequestSendNotify = _config.events && !!_config.events.onRequestSendNotify;
  312. _config.editorConfig.mergeFolderUrl = _config.editorConfig.mergeFolderUrl || _config.editorConfig.saveAsUrl;
  313. _config.editorConfig.canRequestSaveAs = _config.events && !!_config.events.onRequestSaveAs;
  314. _config.editorConfig.canRequestInsertImage = _config.events && !!_config.events.onRequestInsertImage;
  315. _config.editorConfig.canRequestMailMergeRecipients = _config.events && !!_config.events.onRequestMailMergeRecipients;
  316. _config.editorConfig.canRequestCompareFile = _config.events && !!_config.events.onRequestCompareFile;
  317. _config.editorConfig.canRequestSharingSettings = _config.events && !!_config.events.onRequestSharingSettings;
  318. _config.editorConfig.canRequestCreateNew = _config.events && !!_config.events.onRequestCreateNew;
  319. _config.frameEditorId = placeholderId;
  320. _config.parentOrigin = window.location.origin;
  321. var onMouseUp = function (evt) {
  322. _processMouse(evt);
  323. };
  324. var _attachMouseEvents = function() {
  325. if (window.addEventListener) {
  326. window.addEventListener("mouseup", onMouseUp, false)
  327. } else if (window.attachEvent) {
  328. window.attachEvent("onmouseup", onMouseUp);
  329. }
  330. };
  331. var _detachMouseEvents = function() {
  332. if (window.removeEventListener) {
  333. window.removeEventListener("mouseup", onMouseUp, false)
  334. } else if (window.detachEvent) {
  335. window.detachEvent("onmouseup", onMouseUp);
  336. }
  337. };
  338. var _onAppReady = function() {
  339. if (_config.type === 'mobile') {
  340. document.body.onfocus = function(e) {
  341. setTimeout(function(){
  342. iframe.contentWindow.focus();
  343. _sendCommand({
  344. command: 'resetFocus',
  345. data: {}
  346. })
  347. }, 10);
  348. };
  349. }
  350. _attachMouseEvents();
  351. if (_config.editorConfig) {
  352. _init(_config.editorConfig);
  353. }
  354. if (_config.document) {
  355. _openDocument(_config.document);
  356. }
  357. };
  358. var _onMessage = function(msg) {
  359. if ( msg ) {
  360. if ( msg.type === "onExternalPluginMessage" ) {
  361. _sendCommand(msg);
  362. } else if (msg.type === "onExternalPluginMessageCallback") {
  363. postMessage(window.parent, msg);
  364. } else
  365. if ( msg.frameEditorId == placeholderId ) {
  366. var events = _config.events || {},
  367. handler = events[msg.event],
  368. res;
  369. if (msg.event === 'onRequestEditRights' && !handler) {
  370. _applyEditRights(false, 'handler isn\'t defined');
  371. } else {
  372. if (msg.event === 'onAppReady') {
  373. _onAppReady();
  374. }
  375. if (handler && typeof handler == "function") {
  376. res = handler.call(_self, {target: _self, data: msg.data});
  377. }
  378. }
  379. }
  380. }
  381. };
  382. var _checkConfigParams = function() {
  383. if (_config.document) {
  384. if (!_config.document.url || ((typeof _config.document.fileType !== 'string' || _config.document.fileType=='') &&
  385. (typeof _config.documentType !== 'string' || _config.documentType==''))) {
  386. window.alert("One or more required parameter for the config object is not set");
  387. return false;
  388. }
  389. var appMap = {
  390. 'text': 'docx',
  391. 'text-pdf': 'pdf',
  392. 'spreadsheet': 'xlsx',
  393. 'presentation': 'pptx',
  394. 'word': 'docx',
  395. 'cell': 'xlsx',
  396. 'slide': 'pptx'
  397. }, app;
  398. if (_config.documentType=='text' || _config.documentType=='spreadsheet' ||_config.documentType=='presentation')
  399. console.warn("The \"documentType\" parameter for the config object must take one of the values word/cell/slide.");
  400. if (typeof _config.documentType === 'string' && _config.documentType != '') {
  401. app = appMap[_config.documentType.toLowerCase()];
  402. if (!app) {
  403. window.alert("The \"documentType\" parameter for the config object is invalid. Please correct it.");
  404. return false;
  405. } else if (typeof _config.document.fileType !== 'string' || _config.document.fileType == '') {
  406. _config.document.fileType = app;
  407. }
  408. }
  409. if (typeof _config.document.fileType === 'string' && _config.document.fileType != '') {
  410. _config.document.fileType = _config.document.fileType.toLowerCase();
  411. var type = /^(?:(xls|xlsx|ods|csv|xlst|xlsy|gsheet|xlsm|xlt|xltm|xltx|fods|ots|xlsb)|(pps|ppsx|ppt|pptx|odp|pptt|ppty|gslides|pot|potm|potx|ppsm|pptm|fodp|otp)|(doc|docx|doct|odt|gdoc|txt|rtf|pdf|mht|htm|html|epub|djvu|xps|oxps|docm|dot|dotm|dotx|fodt|ott|fb2|xml|oform|docxf))$/
  412. .exec(_config.document.fileType);
  413. if (!type) {
  414. window.alert("The \"document.fileType\" parameter for the config object is invalid. Please correct it.");
  415. return false;
  416. } else if (typeof _config.documentType !== 'string' || _config.documentType == ''){
  417. if (typeof type[1] === 'string') _config.documentType = 'cell'; else
  418. if (typeof type[2] === 'string') _config.documentType = 'slide'; else
  419. if (typeof type[3] === 'string') _config.documentType = 'word';
  420. }
  421. }
  422. var type = /^(?:(pdf|djvu|xps|oxps))$/.exec(_config.document.fileType);
  423. if (type && typeof type[1] === 'string') {
  424. _config.editorConfig.canUseHistory = false;
  425. }
  426. if (!_config.document.title || _config.document.title=='')
  427. _config.document.title = 'Unnamed.' + _config.document.fileType;
  428. if (!_config.document.key) {
  429. _config.document.key = 'xxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function (c) {var r = Math.random() * 16 | 0; return r.toString(16);});
  430. } else if (typeof _config.document.key !== 'string') {
  431. window.alert("The \"document.key\" parameter for the config object must be string. Please correct it.");
  432. return false;
  433. }
  434. if (_config.editorConfig.user && _config.editorConfig.user.id && (typeof _config.editorConfig.user.id == 'number')) {
  435. _config.editorConfig.user.id = _config.editorConfig.user.id.toString();
  436. console.warn("The \"id\" parameter for the editorConfig.user object must be a string.");
  437. }
  438. _config.document.token = _config.token;
  439. }
  440. return true;
  441. };
  442. (function() {
  443. var result = /[\?\&]placement=(\w+)&?/.exec(window.location.search);
  444. if (!!result && result.length) {
  445. if (result[1] == 'desktop') {
  446. _config.editorConfig.targetApp = result[1];
  447. // _config.editorConfig.canBackToFolder = false;
  448. if (!_config.editorConfig.customization) _config.editorConfig.customization = {};
  449. _config.editorConfig.customization.about = false;
  450. _config.editorConfig.customization.compactHeader = false;
  451. }
  452. }
  453. })();
  454. var target = document.getElementById(placeholderId),
  455. iframe;
  456. if (target && _checkConfigParams()) {
  457. iframe = createIframe(_config);
  458. if (iframe.src) {
  459. var pathArray = iframe.src.split('/');
  460. this.frameOrigin = pathArray[0] + '//' + pathArray[2];
  461. }
  462. target.parentNode && target.parentNode.replaceChild(iframe, target);
  463. var _msgDispatcher = new MessageDispatcher(_onMessage, this);
  464. }
  465. /*
  466. cmd = {
  467. command: 'commandName',
  468. data: <command specific data>
  469. }
  470. */
  471. var _destroyEditor = function(cmd) {
  472. var target = document.createElement("div");
  473. target.setAttribute('id', placeholderId);
  474. if (iframe) {
  475. _msgDispatcher && _msgDispatcher.unbindEvents();
  476. _detachMouseEvents();
  477. iframe.parentNode && iframe.parentNode.replaceChild(target, iframe);
  478. }
  479. };
  480. var _sendCommand = function(cmd) {
  481. if (iframe && iframe.contentWindow)
  482. postMessage(iframe.contentWindow, cmd);
  483. };
  484. var _init = function(editorConfig) {
  485. _sendCommand({
  486. command: 'init',
  487. data: {
  488. config: editorConfig
  489. }
  490. });
  491. };
  492. var _openDocument = function(doc) {
  493. _sendCommand({
  494. command: 'openDocument',
  495. data: {
  496. doc: doc
  497. }
  498. });
  499. };
  500. var _showMessage = function(title, msg) {
  501. msg = msg || title;
  502. _sendCommand({
  503. command: 'showMessage',
  504. data: {
  505. msg: msg
  506. }
  507. });
  508. };
  509. var _applyEditRights = function(allowed, message) {
  510. _sendCommand({
  511. command: 'applyEditRights',
  512. data: {
  513. allowed: allowed,
  514. message: message
  515. }
  516. });
  517. };
  518. var _processSaveResult = function(result, message) {
  519. _sendCommand({
  520. command: 'processSaveResult',
  521. data: {
  522. result: result,
  523. message: message
  524. }
  525. });
  526. };
  527. // TODO: remove processRightsChange, use denyEditingRights
  528. var _processRightsChange = function(enabled, message) {
  529. _sendCommand({
  530. command: 'processRightsChange',
  531. data: {
  532. enabled: enabled,
  533. message: message
  534. }
  535. });
  536. };
  537. var _denyEditingRights = function(message) {
  538. _sendCommand({
  539. command: 'processRightsChange',
  540. data: {
  541. enabled: false,
  542. message: message
  543. }
  544. });
  545. };
  546. var _refreshHistory = function(data, message) {
  547. _sendCommand({
  548. command: 'refreshHistory',
  549. data: {
  550. data: data,
  551. message: message
  552. }
  553. });
  554. };
  555. var _setHistoryData = function(data, message) {
  556. _sendCommand({
  557. command: 'setHistoryData',
  558. data: {
  559. data: data,
  560. message: message
  561. }
  562. });
  563. };
  564. var _setEmailAddresses = function(data) {
  565. _sendCommand({
  566. command: 'setEmailAddresses',
  567. data: {
  568. data: data
  569. }
  570. });
  571. };
  572. var _setActionLink = function (data) {
  573. _sendCommand({
  574. command: 'setActionLink',
  575. data: {
  576. url: data
  577. }
  578. });
  579. };
  580. var _processMailMerge = function(enabled, message) {
  581. _sendCommand({
  582. command: 'processMailMerge',
  583. data: {
  584. enabled: enabled,
  585. message: message
  586. }
  587. });
  588. };
  589. var _downloadAs = function(data) {
  590. _sendCommand({
  591. command: 'downloadAs',
  592. data: data
  593. });
  594. };
  595. var _setUsers = function(data) {
  596. _sendCommand({
  597. command: 'setUsers',
  598. data: data
  599. });
  600. };
  601. var _showSharingSettings = function(data) {
  602. _sendCommand({
  603. command: 'showSharingSettings',
  604. data: data
  605. });
  606. };
  607. var _setSharingSettings = function(data) {
  608. _sendCommand({
  609. command: 'setSharingSettings',
  610. data: data
  611. });
  612. };
  613. var _insertImage = function(data) {
  614. _sendCommand({
  615. command: 'insertImage',
  616. data: data
  617. });
  618. };
  619. var _setMailMergeRecipients = function(data) {
  620. _sendCommand({
  621. command: 'setMailMergeRecipients',
  622. data: data
  623. });
  624. };
  625. var _setRevisedFile = function(data) {
  626. _sendCommand({
  627. command: 'setRevisedFile',
  628. data: data
  629. });
  630. };
  631. var _setFavorite = function(data) {
  632. _sendCommand({
  633. command: 'setFavorite',
  634. data: data
  635. });
  636. };
  637. var _requestClose = function(data) {
  638. _sendCommand({
  639. command: 'requestClose',
  640. data: data
  641. });
  642. };
  643. var _processMouse = function(evt) {
  644. var r = iframe.getBoundingClientRect();
  645. var data = {
  646. type: evt.type,
  647. x: evt.x - r.left,
  648. y: evt.y - r.top,
  649. event: evt
  650. };
  651. _sendCommand({
  652. command: 'processMouse',
  653. data: data
  654. });
  655. };
  656. var _grabFocus = function(data) {
  657. setTimeout(function(){
  658. _sendCommand({
  659. command: 'grabFocus',
  660. data: data
  661. });
  662. }, 10);
  663. };
  664. var _blurFocus = function(data) {
  665. _sendCommand({
  666. command: 'blurFocus',
  667. data: data
  668. });
  669. };
  670. var _serviceCommand = function(command, data) {
  671. _sendCommand({
  672. command: 'internalCommand',
  673. data: {
  674. command: command,
  675. data: data
  676. }
  677. });
  678. };
  679. return {
  680. showMessage : _showMessage,
  681. processSaveResult : _processSaveResult,
  682. processRightsChange : _processRightsChange,
  683. denyEditingRights : _denyEditingRights,
  684. refreshHistory : _refreshHistory,
  685. setHistoryData : _setHistoryData,
  686. setEmailAddresses : _setEmailAddresses,
  687. setActionLink : _setActionLink,
  688. processMailMerge : _processMailMerge,
  689. downloadAs : _downloadAs,
  690. serviceCommand : _serviceCommand,
  691. attachMouseEvents : _attachMouseEvents,
  692. detachMouseEvents : _detachMouseEvents,
  693. destroyEditor : _destroyEditor,
  694. setUsers : _setUsers,
  695. showSharingSettings : _showSharingSettings,
  696. setSharingSettings : _setSharingSettings,
  697. insertImage : _insertImage,
  698. setMailMergeRecipients: _setMailMergeRecipients,
  699. setRevisedFile : _setRevisedFile,
  700. setFavorite : _setFavorite,
  701. requestClose : _requestClose,
  702. grabFocus : _grabFocus,
  703. blurFocus : _blurFocus
  704. }
  705. };
  706. DocsAPI.DocEditor.defaultConfig = {
  707. type: 'desktop',
  708. width: '100%',
  709. height: '100%',
  710. editorConfig: {
  711. lang: 'en',
  712. canCoAuthoring: true,
  713. customization: {
  714. about: true,
  715. feedback: false
  716. }
  717. }
  718. };
  719. DocsAPI.DocEditor.version = function() {
  720. return '7.1.1';
  721. };
  722. MessageDispatcher = function(fn, scope) {
  723. var _fn = fn,
  724. _scope = scope || window,
  725. eventFn = function(msg) {
  726. _onMessage(msg);
  727. };
  728. var _bindEvents = function() {
  729. if (window.addEventListener) {
  730. window.addEventListener("message", eventFn, false)
  731. }
  732. else if (window.attachEvent) {
  733. window.attachEvent("onmessage", eventFn);
  734. }
  735. };
  736. var _unbindEvents = function() {
  737. if (window.removeEventListener) {
  738. window.removeEventListener("message", eventFn, false)
  739. }
  740. else if (window.detachEvent) {
  741. window.detachEvent("onmessage", eventFn);
  742. }
  743. };
  744. var _onMessage = function(msg) {
  745. // TODO: check message origin
  746. if (msg && window.JSON && _scope.frameOrigin==msg.origin ) {
  747. try {
  748. var msg = window.JSON.parse(msg.data);
  749. if (_fn) {
  750. _fn.call(_scope, msg);
  751. }
  752. } catch(e) {}
  753. }
  754. };
  755. _bindEvents.call(this);
  756. return {
  757. unbindEvents: _unbindEvents
  758. }
  759. };
  760. function getBasePath() {
  761. var scripts = document.getElementsByTagName('script'),
  762. match;
  763. for (var i = scripts.length - 1; i >= 0; i--) {
  764. match = scripts[i].src.match(/(.*)api\/documents\/api.js/i);
  765. if (match) {
  766. return match[1];
  767. }
  768. }
  769. return "";
  770. }
  771. function getExtensionPath() {
  772. if ("undefined" == typeof(extensionParams) || null == extensionParams["url"])
  773. return null;
  774. return extensionParams["url"] + "apps/";
  775. }
  776. function getTestPath() {
  777. var scripts = document.getElementsByTagName('script'),
  778. match;
  779. for (var i = scripts.length - 1; i >= 0; i--) {
  780. match = scripts[i].src.match(/(.*)apps\/api\/documents\/api.js/i);
  781. if (match) {
  782. return match[1] + "test/";
  783. }
  784. }
  785. return "";
  786. }
  787. function getAppPath(config) {
  788. var extensionPath = getExtensionPath(),
  789. path = extensionPath ? extensionPath : (config.type=="test" ? getTestPath() : getBasePath()),
  790. appMap = {
  791. 'text': 'documenteditor',
  792. 'text-pdf': 'documenteditor',
  793. 'spreadsheet': 'spreadsheeteditor',
  794. 'presentation': 'presentationeditor',
  795. 'word': 'documenteditor',
  796. 'cell': 'spreadsheeteditor',
  797. 'slide': 'presentationeditor'
  798. },
  799. app = appMap['word'];
  800. if (typeof config.documentType === 'string') {
  801. app = appMap[config.documentType.toLowerCase()];
  802. } else
  803. if (!!config.document && typeof config.document.fileType === 'string') {
  804. var type = /^(?:(xls|xlsx|ods|csv|xlst|xlsy|gsheet|xlsm|xlt|xltm|xltx|fods|ots|xlsb)|(pps|ppsx|ppt|pptx|odp|pptt|ppty|gslides|pot|potm|potx|ppsm|pptm|fodp|otp))$/
  805. .exec(config.document.fileType);
  806. if (type) {
  807. if (typeof type[1] === 'string') app = appMap['cell']; else
  808. if (typeof type[2] === 'string') app = appMap['slide'];
  809. }
  810. }
  811. var userAgent = navigator.userAgent.toLowerCase(),
  812. check = function(regex){ return regex.test(userAgent); },
  813. isIE = !check(/opera/) && (check(/msie/) || check(/trident/) || check(/edge/)),
  814. isChrome = !isIE && check(/\bchrome\b/),
  815. isSafari_mobile = !isIE && !isChrome && check(/safari/) && (navigator.maxTouchPoints>0),
  816. path_type;
  817. path += app + "/";
  818. path_type = (config.type === "mobile" || isSafari_mobile)
  819. ? "mobile" : (config.type === "embedded")
  820. ? "embed" : (config.document && typeof config.document.fileType === 'string' && config.document.fileType.toLowerCase() === 'oform')
  821. ? "forms" : "main";
  822. path += path_type;
  823. var index = "/index.html";
  824. if (config.editorConfig && path_type!=="forms") {
  825. var customization = config.editorConfig.customization;
  826. if ( typeof(customization) == 'object' && ( customization.toolbarNoTabs ||
  827. (config.editorConfig.targetApp!=='desktop') && (customization.loaderName || customization.loaderLogo))) {
  828. index = "/index_loader.html";
  829. } else if (config.editorConfig.mode === 'editdiagram' || config.editorConfig.mode === 'editmerge')
  830. index = "/index_internal.html";
  831. }
  832. path += index;
  833. return path;
  834. }
  835. function getAppParameters(config) {
  836. var params = "?_dc=7.1.1-23";
  837. if (config.editorConfig && config.editorConfig.lang)
  838. params += "&lang=" + config.editorConfig.lang;
  839. if (config.editorConfig && config.editorConfig.targetApp!=='desktop') {
  840. if ( (typeof(config.editorConfig.customization) == 'object') && config.editorConfig.customization.loaderName) {
  841. if (config.editorConfig.customization.loaderName !== 'none') params += "&customer=" + encodeURIComponent(config.editorConfig.customization.loaderName);
  842. } else
  843. params += "&customer=ONLYOFFICE";
  844. if (typeof(config.editorConfig.customization) == 'object') {
  845. if ( config.editorConfig.customization.loaderLogo && config.editorConfig.customization.loaderLogo !== '') {
  846. params += "&logo=" + encodeURIComponent(config.editorConfig.customization.loaderLogo);
  847. }
  848. if ( config.editorConfig.customization.logo ) {
  849. if (config.type=='embedded' && (config.editorConfig.customization.logo.image || config.editorConfig.customization.logo.imageEmbedded))
  850. params += "&headerlogo=" + encodeURIComponent(config.editorConfig.customization.logo.image || config.editorConfig.customization.logo.imageEmbedded);
  851. else if (config.type!='embedded' && (config.editorConfig.customization.logo.image || config.editorConfig.customization.logo.imageDark)) {
  852. config.editorConfig.customization.logo.image && (params += "&headerlogo=" + encodeURIComponent(config.editorConfig.customization.logo.image));
  853. config.editorConfig.customization.logo.imageDark && (params += "&headerlogodark=" + encodeURIComponent(config.editorConfig.customization.logo.imageDark));
  854. }
  855. }
  856. }
  857. }
  858. if (config.editorConfig && (config.editorConfig.mode == 'editdiagram' || config.editorConfig.mode == 'editmerge'))
  859. params += "&internal=true";
  860. if (config.frameEditorId)
  861. params += "&frameEditorId=" + config.frameEditorId;
  862. if (config.editorConfig && config.editorConfig.mode == 'view' ||
  863. config.document && config.document.permissions && (config.document.permissions.edit === false && !config.document.permissions.review ))
  864. params += "&mode=view";
  865. if (config.editorConfig && config.editorConfig.customization && !!config.editorConfig.customization.compactHeader)
  866. params += "&compact=true";
  867. if (config.editorConfig && config.editorConfig.customization && (config.editorConfig.customization.toolbar===false))
  868. params += "&toolbar=false";
  869. if (config.parentOrigin)
  870. params += "&parentOrigin=" + config.parentOrigin;
  871. if (config.editorConfig && config.editorConfig.customization && config.editorConfig.customization.uiTheme )
  872. params += "&uitheme=" + config.editorConfig.customization.uiTheme;
  873. return params;
  874. }
  875. function getFrameTitle(config) {
  876. var title = 'Powerful online editor for text documents, spreadsheets, and presentations';
  877. var appMap = {
  878. 'text': 'text documents',
  879. 'spreadsheet': 'spreadsheets',
  880. 'presentation': 'presentations',
  881. 'word': 'text documents',
  882. 'cell': 'spreadsheets',
  883. 'slide': 'presentations'
  884. };
  885. if (typeof config.documentType === 'string') {
  886. var app = appMap[config.documentType.toLowerCase()];
  887. if (app)
  888. title = 'Powerful online editor for ' + app;
  889. }
  890. return title;
  891. }
  892. function createIframe(config) {
  893. var iframe = document.createElement("iframe");
  894. iframe.src = getAppPath(config) + getAppParameters(config);
  895. iframe.width = config.width;
  896. iframe.height = config.height;
  897. iframe.align = "top";
  898. iframe.frameBorder = 0;
  899. iframe.name = "frameEditor";
  900. iframe.title = getFrameTitle(config);
  901. iframe.allowFullscreen = true;
  902. iframe.setAttribute("allowfullscreen",""); // for IE11
  903. iframe.setAttribute("onmousewheel",""); // for Safari on Mac
  904. iframe.setAttribute("allow", "autoplay; camera; microphone; display-capture");
  905. if (config.type == "mobile")
  906. {
  907. iframe.style.position = "fixed";
  908. iframe.style.overflow = "hidden";
  909. document.body.style.overscrollBehaviorY = "contain";
  910. }
  911. return iframe;
  912. }
  913. function postMessage(wnd, msg) {
  914. if (wnd && wnd.postMessage && window.JSON) {
  915. // TODO: specify explicit origin
  916. wnd.postMessage(window.JSON.stringify(msg), "*");
  917. }
  918. }
  919. function extend(dest, src) {
  920. for (var prop in src) {
  921. if (src.hasOwnProperty(prop)) {
  922. if (typeof dest[prop] === 'undefined') {
  923. dest[prop] = src[prop];
  924. } else
  925. if (typeof dest[prop] === 'object' &&
  926. typeof src[prop] === 'object') {
  927. extend(dest[prop], src[prop])
  928. }
  929. }
  930. }
  931. return dest;
  932. }
  933. })(window.DocsAPI = window.DocsAPI || {}, window, document);