Refresh a webpage just once after 5 seconds - refresh

I'm looking for a JavaScript solution (or whatever else) that will refresh a webpage ONLY once, after 5 seconds it has been opened. Is this possible without being stuck in a refresh loop?

try this:
setTimeout(function ()
{
if (self.name != '_refreshed_'){
self.name = '_refreshed_';
self.location.reload(true);
} else {
self.name = '';
}
}, 5000);

You could do this in many different ways, but I think the easiest would be to add a query string to the url after the refresh, allowing us to tell if the refresh has already occurred:
//Function to get query string value. Source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
//check if our query string is already set:
if(getQuerystring(r) !== 1){
setTimeout(function(){window.location.href = window.location.href + '?r=1'},5000)
}
If there is the possibility that a query string is already present, you will have to account for that and change the '?' to an '&'.

Sure, if you don't mind using jquery you can do it via an ajax call after waiting 5 seconds. Just throwing you some sample code:
How to wait 5 seconds with jQuery?
$(document).ready(function() {
// Get data
$.ajax({
url : '/tommyStockExchange/Data',
dataType : 'html',
data : {
'format' : 'H',
'type' : 'E'
},
success : function(data) {
$("#executions").html(data);
},
statusCode : {
404 : function() {
alert('executions url 404 :(');
}
}
});
});

Make it redirect to the same page with a different #hash and in JS only register the redirect if the hash isn't set.

You just need to pass some sort of data between page loads. This can be done in a multitude of ways — use a cookie, a URL query parameter, or something on the server side. Query parameter example:
if (!location.search.match(/(\?|&|^)stopRefreshing(=|&|$)/))
{
setTimeout(function ()
{
var search = location.search;
location.search = search ? search + '&stopRefreshing' : 'stopRefreshing';
}, 5000);
}
Demo: http://jsbin.com/ofawuz/edit

Related

Sharepoint: How to show AppendOnlyHistory on a display template in a cross-publishing scenario

The overarching requirement I am trying to implement is to show comments (made on a list, item by item basis).
I added the feature on the authoring side by enabling versioning on the list and adding a text field with the option "Append Changes to Existing Text" set to true.
This indeed allows me to comment on items and displays them chronologically, but on the authoring side only.
The issue is that the UI part will be done on another site collection and I can't find a straightforward way to get all comments there.
So far, every resource I have found points to
<SharePoint:AppendOnlyHistory runat="server" FieldName="YourCommentsFieldName" ControlMode="Display"/>
The thing is, I can't (don't know how to) use this inside a display template.
So far, I am getting all my data using the REST API, via
var siteUrl=_spPageContextInfo.webAbsoluteUrl.replace("publishing","authoring");
$.ajax({
url: siteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
type: 'GET',
async:false,
headers: {"accept": "application/json;odata=verbose",},
dataType: 'JSON',
success: function(json) {
console.log(json);
//var obj = $.parseJSON(JSON.stringify(json.d.results));
//alert(obj);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error :"+XMLHttpRequest.responseText);
}
});
What this gives me is the latest comment only. I need a simple way to get a hold of the entire thread.
I ended up using javascript object model to get them like so:
function GetComments(listname, itemId) {
var siteUrl = _spPageContextInfo.webAbsoluteUrl.replace("publishing", "authoring");
if ($(".comments-history").length) {
$().SPServices({
operation: "GetVersionCollection",
async: false,
webURL: siteUrl,
strlistID: listname,
strlistItemID: itemId,
strFieldName: "Comments",
completefunc: function (xData, Status) {
$(xData.responseText).find("Version").each(function (data, i) {
var xmlComment = $(this)[0].outerHTML;
var arr = xmlComment.split(/comments|modified|editor/g);
var comment = arr[1].trim().substring(2, arr[1].length-2);
var dateSt = Date.parse((arr[2].substring(1, arr[2].length)).replace('/"', ''));
var user = getUsername(arr[3]);
var st = "<div class='comment-item'><div class='comment-user'>" + user + "(" + FormatDate(dateSt) + ")</div>";
st += "<div class='comment-text'>" + comment + "</div></div>";
$(".comments-history").append(st);
});
}
});
}
}
the parsing could be better, but this is just an initial working idea

How can I get and set cookies inside webview tag of nwjs?

So my app just open a new window of a local html file with a webview tag of some webpage. But when I tried to get the cookies, I cannot get anything.I think the reason is the cookie is bounded to the url of the webview tag but now my local file but when I can only get the window of the local file.How can I solve this problem?
it might be late but i will answer this for future visitors :P
I think the best and the direct way to set and get cookies without any workarounds is to use webview request interceptors and change the request and response headers this is more secure and reliable and will work in nodewebkit, electron and chromium extensions and apps:
So to set headers you can use onBeforeSendHeaders,
for example lets say you want to change a cookie called "connect.sid" that used as session id in expressjs you can do the following:
var new_sessionId = "s%randskbksbdfmnsdbf345k345h34k5";
var $webview = $("#my-webview");
$webview.get(0).request.onBeforeSendHeaders.addListener(
function (details) {
details.requestHeaders.forEach(function (header) {
if (header.name === "Cookie") {
var cookies = header.value.split("; ");
var valid_cookies = cookies.filter(function (cookie) {
return cookie && cookie.indexOf("connect.sid") < 0;
});
valid_cookies.push("connect.sid=" + new_sessionId);
header.value = valid_cookies.join("; ");
}
});
return {requestHeaders: details.requestHeaders};
},
{urls: ["<all_urls>"]},
["blocking", "requestHeaders"]
);
$webview.attr("src","http://example.com");
and to read headers you can use onHeadersReceived
var $webview = $("#my-webview");
$webview.get(0).request.onHeadersReceived.addListener(function (details) {
details.responseHeaders.forEach(function (header) {
if (header.name === "set-cookie") {
var cookies = header.value.split("; ");
var sessionCookie = cookies.find(function (cookie) {
return cookie && cookie.indexOf("connect.sid") === 0;
});
if (sessionCookie) {
var sessionId = sessionCookie.split("=")[1];
console.log(sessionId);
}
}
});
},
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]
);
$webview.attr("src","http://example.com");
Note: you can also set and get cookies for your main window using this method but instead of intercepting webview.request you can intercept chrome.webRequest or just use chrome.cookies.set and chrome.cookies.get, i found all these things in chromium source code ;)

Bootstrap 3 typeahead.js - remote url attributes

I'm trying to call my remote url with added attributes to the url.
For now I have this working:
$('#league').typeahead({
remote: '/typeahead/get_league?query=%QUERY',
limit: 10
});
Now I would like to do something like this:
$('#league').typeahead({
remote: function () {
var q = '/typeahead/get_league?query=%QUERY';
if ($('#sport').val())
q += "&sport=" + encodeURIComponent($('#sport').val());
return base_url + q;
},
limit: 10
});
I would like to add the GET attribute 'sport' to the URL so I can narrow down my query on the backend. I tried the code above but I get a JS error.
The previous version of Bootstrap Typeahead allowed this type of setup. It was very useful as I could update the remote URL every time a key get hit.
Any idea how to make that work for this version ?
remote is exclusively for typeahead.js (not part of Bootstrap). But you are not using the remote correctly, it can be either a string or an object, not a function.
When you need to change the request URL, you can use replace:
$('#league').typeahead({
remote: {
url: '/typeahead/get_league?query=%QUERY',
replace: function () {
var q = '/typeahead/get_league?query=%QUERY';
if ($('#sport').val()) {
q += "&sport=" + encodeURIComponent($('#sport').val());
}
return base_url + q;
}
},
limit: 10
});
Check the docs here
Hope it helps.
Hieu Nguyen solution will not work for %QUERY wildcards.
According to Bloodhound.js documentation,
replace – .... If set, no wildcard substitution will be performed on url.
Bloodhound docs on github
So %QUERY will be passed as string without being replaced by text entered from user.
So you should put typeahead value into your url :
$('#league').typeahead({
remote: {
url: '/typeahead/get_league?query=%QUERY',
replace: function () {
var q = '/typeahead/get_league?query=' + $('#league').val();
if ($('#sport').val()) {
q += "&sport=" + encodeURIComponent($('#sport').val());
}
return base_url + q;
}
},
limit: 10
});
Here is a complete example with the QUERY result as well passed. Note that when the remote method is used variable substitution no longer functions. Thanks to hieu-nguyen for the majority of it!
jQuery('#city').typeahead({
name: "cities",
remote: {
url: current_web_root + '?action=ajax|getcities&query=%QUERY',
replace: function () {
var q = current_web_root + '?action=ajax|getcities&query=' + jQuery('#city').val();
if (jQuery('#state').val()) {
q += "&state=" + encodeURIComponent(jQuery('#state').val());
}
return q;
}
},
cache: false
});
jQuery("#state").change(function (e) {
jQuery('#city').val("");
});

How to route after calling commit()

I am struggling a little with what to do after I call commit(). I want to determine how to route the user, depending on commit() being successful or if the server returns an error.
I read somewhere that if there is an error on the server then it can return a status code of >400 and errors as follows:
{ 'errors' : [ { 'errorCode' : [ 'duplicate-user' ] } ] }
On the client-side I have the following:
App.UsersController = Ember.ObjectController.extend({
createUser : function () {
'use strict';
var user = App.User.createRecord({
firstName : $("#firstName").val(),
lastName : $("#lastName").val(),
primaryEmailAddress : $("#primaryEmailAddress").val(),
password : $("#password").val()
}),
commitObserver = Ember.Object.extend({
removeObservers : function (sender) {
sender.removeObserver('isError', this, 'error');
sender.removeObserver('isValid', this, 'success');
},
error : function (sender, key, value) {
this.removeObservers(sender);
App.Router.router.transitionTo('duplicateuser');
},
success : function (sender, key, value) {
this.removeObservers(sender);
App.Router.router.transitionTo('usercreated');
}
});
user.get('transaction').commit();
user.addObserver('isError', commitObserver.create(), 'error');
user.addObserver('isValid', commitObserver.create(), 'success');
}
});
(Note: I am not using 'Ember.TextField' in my HTML hence the use of jQuery)
I have a few questions:
Is this the correct/best approach for handling commit()?
I've found I have to remove both observers as isValid is called after isError - is this to be expected?
How/can I access the server response as I want to be able to make a routing decision based on the error code?
The only way I can reference the router is through App.Router.router - is there a cleaner way?
If there is an error, do I need to do anything to remove the record from the store so it doesn't re-committed in the future?
From within a controller, you can do this:
this.get('target').transitionTo('another.route')
or, you can send an event to the current route and transition from there:
this.get('target').send('eventName');
or if you need to pass a model:
this.get('target').send('eventName', this.get('content'));
Simply use controller.transitionToRoute("your.route");
See this link for the source code...

Facebook FQLproblem with javascript sdk

Hey everyone,
i do the following query to get a user statuses:
FB.api(
{
method: 'fql.query',
query: 'SELECT message FROM statuses WHERE uid = ' + userId
},
function(data) {
// do something with the response
}
);
It works great when the number of result are more than 0.
but when there are no results, the callback function is not called at all.
i need to know if there are 0 rows returning from this query, is there any way to do it?
Thanks :)
First of all, the statuses table does not exists. You should be using status table.
The callback is always called but you should properly check against empty objects. Just paste this on the Javascript Test Console:
<fb:login-button scope="read_stream">
Grant access to statuses
</fb:login-button>
<button onclick="getStatuses()">Get Statuses</button>
<script>
window.getStatuses = function() {
FB.api(
{
method: 'fql.query',
query: 'SELECT message FROM status WHERE uid = me() AND time < 315532800'
},
function(data) {
if(!isEmpty(data)) {
for(var key in data) {
var obj = data[key];
console.log(obj['message'])
}
} else {
console.log("data is empty")
}
});
};
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
</script>
Here I am checking for statuses before 1/1/1980 to insure that an empty result is returned. In your console you should note the data is empty response.
When there are no results from a query, you should be getting an empty array.
Also, there isn't a FQL table named "statuses", it's "status".