1 // This file is part of Moodle - http://moodle.org/
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.
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() {
18 if (typeof XMLHttpRequest != 'undefined') {
19 httpReq = new XMLHttpRequest();
22 httpReq = new ActiveXObject("Msxml2.XMLHTTP.4.0");
25 httpReq = new ActiveXObject("Msxml2.XMLHTTP");
28 httpReq = new ActiveXObject("Microsoft.XMLHTTP");
40 * @param {XMLHttpRequest} httpReq
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|*}
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;
57 * Returns true if we are able to use the Beacon API in this browser.
60 var canUseBeaconAPI = function() {
61 return (allowBeaconAPI && navigator && navigator.sendBeacon && FormData);
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.
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;
78 return (window.mod_scorm_useBeaconAPI && canUseBeaconAPI());
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.
85 * @param {string} param
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('&'),
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);
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) {
114 url += '?api=beacon';
116 url += '&api=beacon';
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);
122 if (console && console.log) {
123 console.log('mod_scorm: Failed to queue navigator.sendBeacon request');
127 // This is what a success looks like when it comes back from the server.
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);
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');
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.';
149 console.log(message);
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);
159 if (httpReq.status == 200) {
160 //popupwin(url+"\n"+param+"\n"+httpReq.responseText);
161 return httpReq.responseText;
163 return httpReq.status;
167 function popupwin(content) {
168 var op = window.open();
169 op.document.open('text/plain');
170 op.document.write(content);
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.
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:
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');
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.
206 * Turns on the use of the Beacon API.
208 var toggleOn = function() {
209 window.mod_scorm_useBeaconAPI = true;
213 * Turns off the use of the Beacon API.
215 var toggleOff = function() {
216 window.mod_scorm_useBeaconAPI = false;
221 * Required because this patch will be backported.
223 * @param {CallableFunction} callback
225 var observe = function(on, callback) {
226 if (!target.addEventListener) {
227 console.log('Unable to attach page dismissal event listeners');
230 return target.addEventListener(on, callback);
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') {
251 } else if (document.visibilityState === 'hidden') {
256 // Begin monitoring on the main window immediately.
257 mod_scorm_monitorForBeaconRequirement(window);