Timeout XMLHttpRequest - timeout

How can I add a timeout to the following script? I want it to display text as "Timed Out".
var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""
function ajaxpage(url, containerid) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {}
}
} else
return false
document.getElementById(containerid).innerHTML = '<img src="load.gif" border="0"><br><br><strong>Generating Link...</strong>'
page_request.onreadystatechange = function () {
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime()
page_request.open('GET', url + bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = page_request.responseText
else if (page_request.readyState == 4 && (page_request.status == 404 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = '<strong>Unable to load link</strong><br>Please try again in a few moments'
}

using the timeout properties of XMLHttpRequest object for example.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert("ready state = 4");
}
};
xhr.open("POST", "http://www.service.org/myService.svc/Method", true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.timeout = 4000; // Set timeout to 4 seconds (4000 milliseconds)
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send(json);
the above code works for me!
Cheers

Related

Is it possible to get Google Ouath2 access token without setting a redirect URI?

I am trying to implement Google Oauth2 consent screen within a popup but it says redirect URI mismatch. Is there any way where I can set up a web Ouath Client App without setting redirect uri in the dashboard?
I know setting up client type from web to others or application may solve this issue. But I want to implement it for web type only. Is this possible?
<!DOCTYPE html>
<html>
<head>
<script>
'use strict';
var GO2 = function GO2(options) {
if (!options || !options.clientId) {
throw 'You need to at least set the clientId';
}
if (typeof window != 'undefined'){
this._redirectUri = window.location.href.substr(0,
window.location.href.length -
window.location.hash.length)
.replace(/#$/, '');
}
// Save the client id
this._clientId = options.clientId;
// if scope is an array, convert it into a string.
if (options.scope) {
this._scope = Array.isArray(options.scope) ?
options.scope.join(' ') :
options.scope;
}
// rewrite redirect_uri
if (options.redirectUri) {
this._redirectUri = options.redirectUri;
}
// popup dimensions
if (options.popupHeight) {
this._popupHeight = options.popupHeight;
}
if (options.popupWidth) {
this._popupWidth = options.popupWidth;
}
if (options.responseType) {
this._responseType = options.responseType;
}
if (options.accessType) {
this._accessType = options.accessType;
}
};
GO2.receiveMessage = function GO2_receiveMessage() {
var go2;
if (window.opener && window.opener.__windowPendingGO2) {
go2 = window.opener.__windowPendingGO2;
}
if (window.parent && window.parent.__windowPendingGO2) {
go2 = window.parent.__windowPendingGO2;
}
var hash = window.location.hash;
if (go2 && hash.indexOf('access_token') !== -1) {
go2._handleMessage(
hash.replace(/^.*access_token=([^&]+).*$/, '$1'),
parseInt(hash.replace(/^.*expires_in=([^&]+).*$/, '$1'), 10),
hash.replace(/^.*state=go2_([^&]+).*$/, '$1')
);
}
if (go2 && window.location.search.indexOf('code=')) {
go2._handleMessage(
window.location.search.replace(/^.*code=([^&]+).*$/, '$1'),
null,
window.location.search.replace(/^.*state=go2_([^&]+).*$/, '$1')
);
}
if (go2 && window.location.search.indexOf('error=')) {
go2._handleMessage(false);
}
};
GO2.prototype = {
WINDOW_NAME: 'google_oauth2_login_popup',
OAUTH_URL: 'https://accounts.google.com/o/oauth2/v2/auth',
_clientId: undefined,
_scope: 'https://www.googleapis.com/auth/plus.me',
_redirectUri: '',
_popupWindow: null,
_immediateFrame: null,
_stateId: Math.random().toString(32).substr(2),
_accessToken: undefined,
_timer: undefined,
_popupWidth: 500,
_popupHeight: 400,
_responseType: 'token',
_accessType: 'online',
onlogin: null,
onlogout: null,
login: function go2_login(forceApprovalPrompt, immediate) {
if (this._accessToken) {
return;
}
this._removePendingWindows();
window.__windowPendingGO2 = this;
var url = this.OAUTH_URL +
'?response_type=' + this._responseType +
'&access_type='+ encodeURIComponent(this._accessType) +
'&redirect_uri=' + encodeURIComponent(this._redirectUri) +
'&scope=' + encodeURIComponent(this._scope) +
'&state=go2_' + this._stateId +
'&client_id=' + encodeURIComponent(this._clientId);
console.log(url);
if (!immediate && forceApprovalPrompt) {
url += '&approval_prompt=force';
}
if (immediate) {
url += '&approval_prompt=auto';
// Open up an iframe to login
// We might not be able to hear any of the callback
// because of X-Frame-Options.
var immediateFrame =
this._immediateFrame = document.createElement('iframe');
immediateFrame.src = url;
immediateFrame.hidden = true;
immediateFrame.width = immediateFrame.height = 1;
immediateFrame.name = this.WINDOW_NAME;
document.body.appendChild(immediateFrame);
return;
}
// Open the popup
var left =
window.screenX + (window.outerWidth / 2) - (this._popupWidth / 2);
var top =
window.screenY + (window.outerHeight / 2) - (this._popupHeight / 2);
var windowFeatures = 'width=' + this._popupWidth +
',height=' + this._popupHeight +
',top=' + top +
',left=' + left +
',location=no,toolbar=no,menubar=no';
this._popupWindow = window.open(url, this.WINDOW_NAME, windowFeatures);
},
logout: function go2_logout() {
if (!this._accessToken) {
return;
}
this._removePendingWindows();
clearTimeout(this._timer);
this._accessToken = undefined;
if (this.onlogout) {
this.onlogout();
}
},
getAccessToken: function go2_getAccessToken() {
return this._accessToken;
},
// receive token from popup / frame
_handleMessage: function go2_handleMessage(token, expiresIn, stateId) {
if (this._stateId !== stateId) {
return;
}
this._removePendingWindows();
// Do nothing if there is no token received.
if (!token) {
return;
}
this._accessToken = token;
if (this.onlogin) {
this.onlogin(this._accessToken);
}
if (expiresIn) {
// Remove the token if timed out.
clearTimeout(this._timer);
this._timer = setTimeout(
function tokenTimeout() {
this._accessToken = undefined;
if (this.onlogout) {
this.onlogout();
}
}.bind(this),
expiresIn * 1000
);
}
},
destory: function go2_destory() {
if (this._timer) {
clearTimeout(this._timer);
}
this._removePendingWindows();
},
_removePendingWindows: function go2_removePendingWindows() {
if (this._immediateFrame) {
document.body.removeChild(this._immediateFrame);
this._immediateFrame = null;
}
if (this._popupWindow) {
this._popupWindow.close();
this._popupWindow = null;
}
if (window.__windowPendingGO2 === this) {
delete window.__windowPendingGO2;
}
}
};
// if the context is the browser
if (typeof window !== 'undefined') {
// If the script loads in a popup matches the WINDOW_NAME,
// we need to handle the request instead.
if (window.name === GO2.prototype.WINDOW_NAME) {
GO2.receiveMessage();
}
}
// Expose the library as an AMD module
if (typeof define === 'function' && define.amd) {
define('google-oauth2-web-client', [], function () { return GO2; });
} else if (typeof module === 'object' && typeof require === 'function') {
// export GO2 in Node.js, assuming we are being browserify'd.
module.exports = GO2;
if (require.main === module) {
console.error('Error: GO2 is not meant to be executed directly.');
}
} else {
window.GO2 = GO2;
}
function test(){
var go2 = new GO2({
clientId: 'dfsdffdfgsfsdfggdgd.apps.googleusercontent.com',
redirectUri: 'http://localhost:8888/gapi/test.html',
responseType: 'code',
accessType: 'offline'
});
go2.login();
}
</script>
</head>
<body>
<a href='#' onClick='test();'> Click here to login </a>
</body>
</html>
It looks like you're using the implicit grant type which requires a redirect uri with response_type=token.
Can you use the authorization code grant type?
The redirect uri is optional for the authorization code grant type.
https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1

Not able to use the updated value -- Flutter

I'm updating the totalPayable value in else if, but I'm not able to use the updated value anywhere in the code when I call getOrder(). Is it an API problem or what can anyone help me with the code?
else if (isOrderInitiated == false){
getCleintOrderFromApi();
debugPrint("ifelse" + totalPayable.toString());
}
getClientOrderFromApi() {
orders.clear();
totalPayable = 0.0;
api.getCleintOrder().then((list) {
list.forEach((order) {
if(order.is_placed) {
order.status = ORDER_STATUS[0];
} else if(!order.is_placed) {
order.status = ORDER_STATUS[2];
}
debugPrint("ORDER_STATUS from remote" + order.status);
for (var j = 0; j < order.items.length; j++) {
FoodItemOrder item = order.items[j];
totalPayable = totalPayable + item.unitPrice * item.quantity;
debugPrint(" total payable in order "+ totalPayable.toString());
}
orders.add(order);
debugPrint("itemsin order"+orders.last.items.length.toString());
});
currentOrderList.clear();
currentOrderList.addAll(orders);
orderItemsSink.add(orders);
});
}
}
The debugPrint in getClientOrderFromApi() is showing the updated result, but in else if debugPrint(" ifelse "+ totalPayable.toString()); it is not showing the updated value which is why wherever I use totalPayable it is not showing the desired value.
Future<List<Order>> getCleintOrder() async {
MakeOrder clientOrderRequest = MakeOrder(); //currentCafe;
clientOrderRequest.caffeID = currentCafe.caffeId;
clientOrderRequest.tableidtimestamp = currentUser.tableIdTimestamp;
// offset = 160;
String url = BASE_URL + BASE_URL_GET_CLIENT_ORDER;
debugPrint("requesting getCleintOrder --- \n" +
url +
"\n " +
clientOrderRequest.toClietnOrderJson().toString());
var response = await http
.post(
url,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
// HttpHeaders.authorizationHeader : ''
},
body: json.encode(clientOrderRequest.toClietnOrderJson()),
)
.catchError(
(error) {
////debugPrint(error.toString());
return false;
},
);
var jsonObj = json.decode(response.body);
////debugPrint(jsonObj.toString());
List<Order> orders = [];
try {
jsonObj.forEach((newJson) {
List<Order> orderList = (newJson["orders"] as List)
.map((neworderJson) => Order.fromJSON(neworderJson))
.toList().cast<Order>();
orders.addAll(orderList);
});
} catch (e) {
////debugPrint(e.toString());
}
// debugPrint("total client orders " + orders.length.toString());
return orders;
}
This is my api call for refernece.

Cant stream video (PFFile) from parse server

I am having trouble streaming video with my iOS app from URL of a PFFile uploaded in my database. I used Heroku and AWS and I still have the same issue. It used to work fine when the files were hosted in the old parse server.
the PFFile url works fine when I open it in a chrome web browser but not in safari nor in the iOS app.
the following is the link of the video:
http://shuuapp.herokuapp.com/parse/files/wnQeou0L4klDelSEtMOX6SxXRVKu1f3sKl6vg349/24092609eadcc049f711aafbd59c1a18_movie.mp4
Its exactly the same issue as the issue mentioned in the link below:
iOS - Can't stream video from Parse Backend
parse-server doesn't seem to be supporting streaming in Safari/iOS and the solution is the enable it using express & GridStore as follows,
parse-server-example\node_modules\parse-server\lib\Routers\FilesRouter
{
key: 'getHandler',
value: function getHandler(req, res, content) {
var config = new _Config2.default(req.params.appId);
var filesController = config.filesController;
var filename = req.params.filename;
var video = '.mp4'
var lastFourCharacters = video.substr(video.length - 4);
if (lastFourCharacters == '.mp4') {
filesController.handleVideoStream(req, res, filename).then(function (data) {
}).catch(function (err) {
console.log('404FilesRouter');
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}else{
filesController.getFileData(config, filename).then(function (data) {
res.status(200);
res.end(data);
}).catch(function (err) {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
}
}
} , ...
parse-server-example\node_modules\parse-server\lib\Controllers\FilesController
_createClass(FilesController, [{
key: 'getFileData',
value: function getFileData(config, filename) {
return this.adapter.getFileData(filename);
}
},{
key: 'handleVideoStream',
value: function handleVideoStream(req, res, filename) {
return this.adapter.handleVideoStream(req, res, filename);
}
}, ...
parse-server-example\node_modules\parse-server\lib\Adapters\Files\GridStoreAdapter
... , {
key: 'handleVideoStream',
value: function handleVideoStream(req, res, filename) {
return this._connect().then(function (database) {
return _mongodb.GridStore.exist(database, filename).then(function () {
var gridStore = new _mongodb.GridStore(database, filename, 'r');
gridStore.open(function(err, GridFile) {
if(!GridFile) {
res.send(404,'Not Found');
return;
}
console.log('filename');
StreamGridFile(GridFile, req, res);
});
});
})
}
}, ...
Bottom of GridStore Adapter
function StreamGridFile(GridFile, req, res) {
var buffer_size = 1024 * 1024;//1024Kb
if (req.get('Range') != null) { //was: if(req.headers['range'])
// Range request, partialle stream the file
console.log('Range Request');
var parts = req.get('Range').replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = partialstart ? parseInt(partialstart, 10) : 0;
var end = partialend ? parseInt(partialend, 10) : GridFile.length - 1;
var chunksize = (end - start) + 1;
if(chunksize == 1){
start = 0;
partialend = false;
}
if(!partialend){
if(((GridFile.length-1) - start) < (buffer_size) ){
end = GridFile.length - 1;
}else{
end = start + (buffer_size);
}
chunksize = (end - start) + 1;
}
if(start == 0 && end == 2){
chunksize = 1;
}
res.writeHead(206, {
'Cache-Control': 'no-cache',
'Content-Range': 'bytes ' + start + '-' + end + '/' + GridFile.length,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
});
GridFile.seek(start, function () {
// get GridFile stream
var stream = GridFile.stream(true);
var ended = false;
var bufferIdx = 0;
var bufferAvail = 0;
var range = (end - start) + 1;
var totalbyteswanted = (end - start) + 1;
var totalbyteswritten = 0;
// write to response
stream.on('data', function (buff) {
bufferAvail += buff.length;
//Ok check if we have enough to cover our range
if(bufferAvail < range) {
//Not enough bytes to satisfy our full range
if(bufferAvail > 0)
{
//Write full buffer
res.write(buff);
totalbyteswritten += buff.length;
range -= buff.length;
bufferIdx += buff.length;
bufferAvail -= buff.length;
}
}
else{
//Enough bytes to satisfy our full range!
if(bufferAvail > 0) {
var buffer = buff.slice(0,range);
res.write(buffer);
totalbyteswritten += buffer.length;
bufferIdx += range;
bufferAvail -= range;
}
}
if(totalbyteswritten >= totalbyteswanted) {
// totalbytes = 0;
GridFile.close();
res.end();
this.destroy();
}
});
});
}else{
// res.end(GridFile);
// stream back whole file
res.header('Cache-Control', 'no-cache');
res.header('Connection', 'keep-alive');
res.header("Accept-Ranges", "bytes");
res.header('Content-Type', 'video/mp4');
res.header('Content-Length', GridFile.length);
var stream = GridFile.stream(true).pipe(res);
}
};
P.S
The original answer is given by #Bragegs here - https://github.com/ParsePlatform/parse-server/issues/1440#issuecomment-212815625 .

Detecting TabMove in firefox add-on

Tried out the impl. given in : https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser#Notification when a tab is added or removed
for tracking 'tabmove'. Didn't work.
Would appreciate any help in this regard.
BTW, already tried below code. Only 'TabOpen' event is received. 'TabClose' and 'TabMove' does not work:
var browserWindows = require("sdk/windows").browserWindows;
var activeWindow = browserWindows ? browserWindows.activeWindow : {};
var browserWindow = activeWindow ? require("sdk/view/core").viewFor(activeWindow) : {};
var DOMWindow = browserWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
var exampleTabAdded = function(event) {
var browser = DOMWindow.gBrowser.getBrowserForTab(event.target);
console.log('tab added: '+ event.target);
};
var exampleTabMoved = function(event) {
var browser = DOMWindow.gBrowser.getBrowserForTab(event.target);
console.log('tab moved: '+ event.target);
};
function exampleTabRemoved(event) {
var browser = gBrowser.getBrowserForTab(event.target);
console.log('tab removed: '+ event.target);
}
function exampleTabSelected(event) {
var browser = gBrowser.getBrowserForTab(event.target);
console.log('tab selected: '+ event.target);
}
var container = DOMWindow.gBrowser.tabContainer;
container.addEventListener("TabMove", exampleTabMoved, false);
container.addEventListener("TabOpen", exampleTabAdded, false);
container.addEventListener("TabClose", exampleTabRemoved, false);
container.addEventListener("TabSelect", exampleTabSelected, false);
Thanks
This seems to work. Uses both sdk api's as well as XUL content document.
If there is a better way to handle 'tabmove', please do post the answer.
var tabs = require("sdk/tabs");
var { modelFor } = require("sdk/model/core");
var { viewFor } = require("sdk/view/core");
var tab_utils = require("sdk/tabs/utils");
var contentDocumentMap = new Map();
function mapHighLevelTabToLowLevelContentDocument(tab) {
var lowLevelTab = viewFor(tab);
var browser = tab_utils.getBrowserForTab(lowLevelTab);
return browser.contentDocument;
}
function onOpen(tab) {
tab.on("pageshow", logShow);
tab.on("activate", logActivate);
tab.on("deactivate", logDeactivate);
tab.on("close", logClose);
}
function logShow(tab) {
var contentWindow = mapHighLevelTabToLowLevelContentDocument(tab);
if ((contentWindow.URL === 'about:newtab') || (contentWindow.URL === 'about:blank')) {
return;
}
if (contentDocumentMap.has(contentWindow)) {
return;
}
contentDocumentMap.set(contentWindow, tab.id.toString());
}
function logActivate(tab) {
var contentWindow = mapHighLevelTabToLowLevelContentDocument(tab);
if ((contentWindow.URL === 'about:newtab') || (contentWindow.URL === 'about:blank')) {
return;
}
if (contentDocumentMap.has(contentWindow)) {
return;
}
contentDocumentMap.set(contentWindow, tab.id.toString());
}
function logDeactivate(tab) {
setTimeout(function() {
var windows = require("sdk/windows").browserWindows;
for (let window of windows) {
var activeTabContentWindow = mapHighLevelTabToLowLevelContentDocument(window.tabs.activeTab);
var activeTabId = window.tabs.activeTab.id.toString();
if ((contentDocumentMap.has(activeTabContentWindow)) && (contentDocumentMap.get(activeTabContentWindow) !== activeTabId)) {
console.log('M O V E D. url: '+ window.tabs.activeTab.url);
console.log('from tabid: '+ contentDocumentMap.get(activeTabContentWindow) + ' to tabid: ' + activeTabId);
contentDocumentMap.delete(activeTabContentWindow);
contentDocumentMap.set(activeTabContentWindow, activeTabId);
}
}
}, 150);
}
function logClose(tab) {
var targetTabId = tab.id.toString();
setTimeout(function() {
var windows = require("sdk/windows").browserWindows;
for (let window of windows) {
var activeTabContentWindow = mapHighLevelTabToLowLevelContentDocument(window.tabs.activeTab);
var activeTabId = window.tabs.activeTab.id.toString();
if (contentDocumentMap.has(activeTabContentWindow)) {
if (contentDocumentMap.get(activeTabContentWindow) !== activeTabId) {
console.log('M O V E D. url: '+ window.tabs.activeTab.url);
console.log('from tabid: '+ contentDocumentMap.get(activeTabContentWindow) + ' to tabid: ' + activeTabId);
contentDocumentMap.delete(activeTabContentWindow);
contentDocumentMap.set(activeTabContentWindow, activeTabId);
}
else if (targetTabId === activeTabId){
contentDocumentMap.delete(activeTabContentWindow);
}
}
}
}, 150);
}
tabs.on('open', onOpen);

Google Gears upload: strange error

I've got this very strange error and I don't know how to deal with it.
My setup is a page in which I can select one image file, (gears beta.desktop) and then it should upload. But it doesn't upload, and gives a very strange error which I can't get away. below is my code:
var filesToUpload = null;
function progressEvent(event) {
var bar = $("#progressBar");
var percentage = Math.round((event.loaded / event.total) * 100);
bar.width(percentage + '%');
}
function uploadState() {
if(request.readyState == 4) {
if(request.status != 200) {
alert('ERROR');
} else {
alert('DONE');
}
}
}
function handleFiles(files) {
if(files.length) {
$('#loader').slideDown(500);
var curFile = files[0];
request.open('POST', 'upload.php');
request.setRequestHeader("Content-Disposition", "attachment; filename=\"" + curFile.name + "\"");
request.onreadystatechange = uploadState;
request.upload.onprogress = progressEvent;
request.send(curFile.blob);
}
}
init = function() {
if(!window.google || !google.gears) {
$('body').css('background', 'white');
$('#gearsOn').hide();
$('#gearsOff').show();
return;
}
// verberg 'geen gears' bericht
$('#gearsOff').hide();
// init upload zooi (gears)
desktop = google.gears.factory.create('beta.desktop');
request = google.gears.factory.create('beta.httprequest');
// on click funct
$('#titel').click(function() {
var newtitle = prompt("Voer een titel in voor het album.");
if(newtitle != '' && newtitle != null) {
$(this).text(newtitle);
}
});
$('.addPictures').click(function() {
filesToUpload = null;
var options = { singleFile: true, filter: [ 'image/jpeg', 'image/png'] };
desktop.openFiles(handleFiles, options);
});
};
$(document).ready(init);
It gives the following error:
[Exception... "Component returned failure code: 0x80004001 (NS_ERROR_NOT_IMPLEMENTED) [nsILoadGroup.groupObserver]" nsresult: "0x80004001 (NS_ERROR_NOT_IMPLEMENTED)" location: "JS frame :: file:///Users/Fabian/Library/Application%20Support/Firefox/Profiles/oo132cjy.default/extensions/%7Be3f6c2cc-d8db-498c-af6c-499fb211db97%7D/components/componentCollectorService.js :: anonymous :: line 1155" data: no]
[Break on this error] obj = getIface(request.loadGroup.groupObserver);
The thing is visible at this location: Dynamics Photo
Thanks in advance!!
I get this error when I'm using page speed - extension to firebug. If you use the same try to deactivate this extension.
disabling page speed did not helped... so uninstalled the extension.. and it works

Resources