weekly release 4.5dev
[moodle.git] / mod / scorm / request.js
blob21a1ce0a81d50dbb8215a9fe93193a220707f1f8
1 // This file is part of Moodle - http://moodle.org/
2 //
3 // Moodle is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // Moodle is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16 function NewHttpReq() {
17     var httpReq = false;
18     if (typeof XMLHttpRequest != 'undefined') {
19         httpReq = new XMLHttpRequest();
20     } else {
21         try {
22             httpReq = new ActiveXObject("Msxml2.XMLHTTP.4.0");
23         } catch (e) {
24             try {
25                 httpReq = new ActiveXObject("Msxml2.XMLHTTP");
26             } catch (ee) {
27                 try {
28                     httpReq = new ActiveXObject("Microsoft.XMLHTTP");
29                 } catch (eee) {
30                     httpReq = false;
31                 }
32             }
33         }
34     }
35     return httpReq;
38 /**
39  *
40  * @param {XMLHttpRequest} httpReq
41  * @param {string} url
42  * @param {string} param
43  * @param {boolean} allowBeaconAPI Should the BeaconAPI be used if required? Defaults to true
44  *    If True, and we can use the Beacon API and are should use the beacon API then we will.
45  *    If False, we will not use the Beacon API, even if we expect a synchronous XHR request to fail.
46  * @returns {string|boolean|*}
47  * @constructor
48  */
49 function DoRequest(httpReq, url, param, allowBeaconAPI) {
51     // Default allowBeaconAPI to true. This argument was added to the function late.
52     if (typeof allowBeaconAPI === 'undefined') {
53         allowBeaconAPI = true;
54     }
56     /**
57      * Returns true if we are able to use the Beacon API in this browser.
58      * @returns boolean
59      */
60     var canUseBeaconAPI = function() {
61         return (allowBeaconAPI && navigator && navigator.sendBeacon && FormData);
62     };
64     /**
65      * Returns true if we should use the Beacon API.
66      * We don't use the Beacon API unless we have to as it stiffles our ability to return data on the request.
67      * @returns {boolean}
68      */
69     var useBeaconAPI = function() {
70         if (typeof window.mod_scorm_useBeaconAPI === 'undefined' || window.mod_scorm_useBeaconAPI === false) {
71             // Last ditch effort, the SCORM package may have introduced its own listeners before our listeners.
72             // This is OLD API, window.event is not reliable and is not recommended API.
73             // https://developer.mozilla.org/en-US/docs/Web/API/Window/event
74             if (window.event && ['beforeunload', 'unload', 'pagehide'].indexOf(window.event.type)) {
75                 window.mod_scorm_useBeaconAPI = true;
76             }
77         }
78         return (window.mod_scorm_useBeaconAPI && canUseBeaconAPI());
79     };
81     /**
82      * Uses the Beacon API to communicate this request to the server.
83      * This function always returns a successful result, because we don't get the actual result, the page doesn't wait for it.
84      * @param {string} url
85      * @param {string} param
86      * @returns {string}
87      */
88     var useSendBeacon = function(url, param) {
89         // Ok, old API alert, the param is a URI encoded string. We need to split it and convert it to a supported format.
90         // I've chosen FormData and FormData.append as they are compatible with our supported browsers:
91         //  - https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
92         //  - https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
94         var vars = param.split('&'),
95             i = 0,
96             pair,
97             key,
98             value,
99             formData = new FormData();
100         for (i = 0; i < vars.length; i++) {
101             pair = vars[i].split('=');
102             key = decodeURIComponent(pair[0]);
103             value = decodeURIComponent(pair[1]);
104             formData.append(key, value);
105         }
106         // We'll also inform it that we are unloading, potentially useful in the future.
107         formData.append('unloading', '1');
109         // We're going to add a token to the URL that will identify this request as going to the beacon API.
110         // In the future this would allow our server side scripts to respond differently when the beacon API
111         // is being used, as the response will be discarded.
112         if (url.indexOf('?') === -1) {
113             // First param
114             url += '?api=beacon';
115         } else {
116             url += '&api=beacon';
117         }
119         // The results is true or false, we don't get the response from the server. Make it look like it was a success.
120         var outcome = navigator.sendBeacon(url, formData);
121         if (!outcome) {
122             if (console && console.log) {
123                 console.log('mod_scorm: Failed to queue navigator.sendBeacon request');
124             }
125             return "false\n101";
126         }
127         // This is what a success looks like when it comes back from the server.
128         return "true\n0";
129     };
131     // If we are unloading, and we can use sendBeacon then do that, Chrome does not permit synchronous XHR requests on unload.
132     if (useBeaconAPI()) {
133         return useSendBeacon(url, param);
134     }
136     // httpReq.open (Method("get","post"), URL(string), Asyncronous(true,false))
137     //popupwin(url+"\n"+param);
138     httpReq.open("POST", url,false);
139     httpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
140     try {
141         httpReq.send(param);
142     } catch (e) {
143         if (console && console.log) {
144             // This may be frivolous as during a shutdown the console log will most likely be lost. But it may help someone.
145             var message = 'XHR request from mod_scorm::DoRequest failed';
146             if (canUseBeaconAPI()) {
147                 message += '; attempting to use Beacon API.';
148             }
149             console.log(message);
150         }
151         // The HTTP request failed. We don't know why, but as a last ditch effort, in case we are unloading and haven't detected it
152         // we will attempt to send the request one more time using the Beacon API. This will result in a successful result regardless
153         // of the actual outcome.
154         if (canUseBeaconAPI()) {
155             return useSendBeacon(url, param);
156         }
157         return false;
158     }
159     if (httpReq.status == 200) {
160         //popupwin(url+"\n"+param+"\n"+httpReq.responseText);
161         return httpReq.responseText;
162     } else {
163         return httpReq.status;
164     }
167 function popupwin(content) {
168     var op = window.open();
169     op.document.open('text/plain');
170     op.document.write(content);
171     op.document.close();
175  * Global variable to track whether we should use the Beacon API instead of synchronous XHR.
176  * This gets set to true in situations where we expect synchronoush XHR requests to fail.
177  */
178 window.mod_scorm_useBeaconAPI = false;
181  * We wire up a small marker for the unload events triggered when the user is navigating away or closing the tab.
182  * This is done because Chrome does not allow synchronous XHR requests on the following unload events:
183  *  - beforeunload
184  *  - unload
185  *  - pagehide
186  *  - visibilitychange
187  */
188 function mod_scorm_monitorForBeaconRequirement(target) {
190     if (typeof target.mod_scorm_monitoring_for_beacon_requirement !== 'undefined') {
191         // We're already observing unload events on this target.
192         console.log('mod_scorm: unload event handlers already attached');
193         return;
194     }
195     target.mod_scorm_monitoring_for_beacon_requirement = true;
197     // The navigator.sendBeacon API is available in all browsers EXCEPT Internet Explorer (IE)
198     // Internet explorer should never get past this check.
199     if (!navigator || !navigator.sendBeacon) {
200         // We can't use the BeaconAPI. There is no point in proceeding to observe unload events.
201         // This is done after adding the flag to target, and establishing the window variable.
202         return;
203     }
205     /**
206      * Turns on the use of the Beacon API.
207      */
208     var toggleOn = function() {
209         window.mod_scorm_useBeaconAPI = true;
210     };
212     /**
213      * Turns off the use of the Beacon API.
214      */
215     var toggleOff = function() {
216         window.mod_scorm_useBeaconAPI = false;
217     };
219     /**
220      * Observes an event.
221      * Required because this patch will be backported.
222      * @param {string} on
223      * @param {CallableFunction} callback
224      */
225     var observe = function(on, callback) {
226         if (!target.addEventListener) {
227             console.log('Unable to attach page dismissal event listeners');
228             return null;
229         }
230         return target.addEventListener(on, callback);
231     };
233     // Listen to the three events known to represent an unload operation.
234     observe('beforeunload', toggleOn);
235     observe('unload', toggleOn);
236     observe('pagehide', toggleOn);
238     // Listen to the event fired when navigating to a page and ensure we toggle useBeaconAPI off.
239     // This shouldn't be needed (page should be uncached) but just in case!
240     observe('pageshow', toggleOff);
242     // Finally listen to the visibility change event, and respond to it.
243     // This unfortunately is not ideal, but is required as a SCORM package may also be listening to this and
244     // trying to save content when the user hides the page. As this can occur as part of the page dismissal lifecycle
245     // we also need to ensure we use the Beacon API here.
246     observe('visibilitychange', function() {
247         // Visible means synchronous XHR permitted, use XHR.
248         // Hidden means synchronous XHR not permitted, use Beacon API.
249         if (document.visibilityState === 'visible' || document.visibilityState === 'prerender') {
250             toggleOff();
251         } else if (document.visibilityState === 'hidden') {
252             toggleOn();
253         }
254     });
256 // Begin monitoring on the main window immediately.
257 mod_scorm_monitorForBeaconRequirement(window);