John Giotta kindly gave me this code earlier (on stack overflow) in order to implement a "turn off styles" button on my website (for a university assignment).
function nostyle() {
for (i=0; i<document.styleSheets.length; i++) {
void(document.styleSheets.item(i).disabled=true);
}
}
I was wondering how easy it would be to implement a cookie to remember that this javascript has been applied so that every page navigated after on the site has styles turned off (My knowledge is extremely basic, I am only a first year).
Regards
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
Set your css_disabled cookie
SetCookie('css_disabled', 'true', 100);
To read the cookie:
function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
if (ReadCookie('css_disabled') == 'true') {...
Related
To give you a grasp of what I mean in my title.
Take a look at this code which is before the setInterval stopped working.
var anime = function(){
_.each(db.get('','animedb'), function(site){
var ann = function(){
^ the function is in a var
for (var epid in eps) {
epid = parseInt(epid, 10);
var eptime = (new Date(eps[epid].pubDate[0])*1000)/1000;
if(eptime > site.lastbuilddate){
counter = counter+1;
if(counter < 6){
list.push(font(colors['normal'])+eps[epid].title[0] +' - ['+ utils.secondsToString((new Date() - (eptime+site.delay))/1000, 1)+' ago.]</f>');
}
}
};
^ this is the part that breaks everything after its been edited
var run = setInterval(ann, site.interval*60000);
^ here is the setInterval its at the bottom of the each
anime();
^ here is the call for the whole function that calls the setInterval
The above code is part of an anime announcement for chat rooms owned by anime sites owners using their rss feeds.
The above code works and excuse me for saying this but at this point.
I'm going to say "I have no idea why". Because i really have no idea why setInterval picks and chooses when to work.
I talked to a friend who had more knowledge than me in javascript and time based functions and he said that there are no "conditions" required for setInterval to run.
for (var epid in eps) {
epid = parseInt(epid, 10);
var eptime = (new Date(eps[epid].pubDate[0])*1000)/1000;
if(eptime > site.lastbuilddate){
counter = counter+1;
if(counter < 6){
var url = eps[epid].link.split('//')[1];
var keyword = '';
var words = url.substr(0, url.length-1).split('/').join('-').split('-');
for (var wid in words) {
keyword += words[wid].charAt(0);
}
http.get({hostname:'dev.ilp.moe', port:80, path:'/surl/yourls-api.php?username=usernameremovedforsecurity&password=passwordremovedforsecurity&format=json&action=shorturl&url='+url+'&title='+ctitle+' - '+eps[epid].title[0]+'&keyword='+keyword}, function(r) {
if(r.statusCode === 200) { //200 is success
var b = '';
r.on('data', function(c) {
b += c;
});
r.on('end', function() {
list.push(font(colors['normal'])+eps[epid].title[0] +' - ['+ utils.secondsToString((new Date() - (eptime+site.delay))/1000, 1)+' ago.] - http://dev.ilp.moe/surl/'+keyword+'</f>');
}
}
});
}
}
};
The above code is the part for creating shorturls.
Here is the json DB that is being loaded.
{"0":{"lastbuilddate":1426441081000,"delay":0,"host":"www.animerush.tv","path":"/rss.xml","chats":["animerushtv"],"interval":15},"1":{"lastbuilddate":1424068119000,"delay":28800000,"host":"dubbedanime.tv","path":"/feed/","chats":["dubbed-anime-tv"],"interval":15},"2":{"lastbuilddate":1426415086000,"delay":32400000,"host":"bestanimes.tv","path":"/feed/","chats":["bestanimestv"],"interval":15},"3":{"lastbuilddate":1426434866000,"delay":0,"host":"www.theanime.tv","path":"/feed/","chats":["timecapsule"],"interval":15}}
The recent edit to my code was supposed to implement Shortened links for each episode released using the links provided in the rss feeds from the sites in the database.
The domain http://ilp.moe is my domain.
I have console logged everywhere and tested as much as I possibly could.
At this point I do not understand why the edit is making code that used to be executed by setInterval no longer be executed.
The reason why the code wasn't executed is because the functions were assigned to a variable so they weren't run until it got to setInterval.
When they reach setInterval the errors prevent setInterval from executing (depends on the severity of the error).
after taking the function and just running it without putting it in a var or setInterval and console logging for a bit i found the error was caused by this line
var url = eps[epid].link.split('//')[1];
in this case
eps[epid].link; // === ["http://blah.com/animelolep1"]
my problem was that the var url was trying to split on a list and not a string
here is the fix
var url = eps[epid].link[0].split('//')[1]; // grabs the first item from the list and then splits
I'm running a Wordpress Multisite Installation with two languages: Hebrew and English.
I have a plugin called Geo IP that helps me to redirect users based on their IP country.
But actually I need more.
I would like to save the last language the user choose.
Example :
if a user close the tab of my site on the english language, I would like that when he comes back, he'll get the english language. Vice versa for Hebrew.
I'm not a pro developer, but I think a cookie can be a solution, and I would like the solution to be in JS if possible.
Update: the code I made ! WDYT guys ?
function get_language {
var myLang = getcookie ('language');
if ( myLang == 'hebrew') {
window.location = "http://zeek.me/he/";
}
else if ( myLang == 'english') {
window.location = "http://zeek.me";
}
else {
window.location = "http://zeek.me";
}
}
function set_language(lang) {
var setLang = setcookie ('language', lang, 30);
var englishClick = document.getElementById('#english_lang');
var hebrewClick = document.getElementById('#hebrew_lang');
englishClick.addEventListener('click', function() {
set_language('english');
})
hebrewClick.addEventListener('click', function() {
set_language('hebrew');
})
}
What you guys think ?
Any solution ?
Thanks,
Simon
As you want a solution with Javascript, you should consider the localStorage. Cookies are nice if you want to know the selected language server-side, but if you just need it local, localStorage is better (reasons below).
To set a localStorage item, use
localStorage.setItem(key, value);
and afterwards to view the value, use
localStorage.getItem(key);
localStorage has a few advantages vs. cookies. Some of them are:
Cookies are included with every HTTP request, thereby slowing down your website by sometimes needlessly transmitting the same data over and over
Cookies are included with every HTTP request, thereby sending data unencrypted over the internet
Cookies are limited to about 4 KB of data
Sounds pretty basic, cookies are what you want. You can stick with javascript, or use php cookies. You opted for a javascript solution.
You'll need a few functions to make this work. Here are some examples below, but these are not working code. You'll need to edit them to do the language switching.
function init_language() {
// this function called when no language has been defined yet
var lang = getcookie( 'language' );
if ( lang == 'hebrew' ) hebrew_pls();
}
function switch_language() {
// When the user takes action to change language, ie, clicks a flag icon
if ( selected_language == 'hebrew' ) hebrew_pls();
}
function hebrew_pls() {
set_language('hebrew'); // aka, whatever you want to do
setcookie( 'language', 'hebrew', 30 ); // remember the language for 30 days
}
Here are the cookie functions I've been using for awhile. It's based on "How do I create and read a value from cookie?". I have modified these so they are a bit easier to use. If you don't like my modifications, there are plenty of alternatives online. Unfortunately JavaScript does not have an easy way to store cookies by default (without third party plugins/scripts).
/*
setCookie( name, value, days, [path = "/"] )
Sets a cookie, expires after "days" have passed
getCookie( name, default )
Gets the value of a cookie, or returns "default". Note: Does not set the cookie to default.
*/
function setCookie(c_name, value, exdays, path) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : ("; expires=" + exdate.toUTCString()));
document.cookie = c_name + "=" + c_value + ((path == null) ? "; path=/" : "; path=" + path);
}
function getCookie(c_name, c_default) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
if (typeof c_default != 'undefined') return c_default;
return false;
}
Starting using a rule and a simple javascript in Alfresco is quite easy but i'm stuck on trying to start a workflow through javascript adding a resource.
My goal is to add the document (or documents) used to start the flow, so i can obtain a reference in the "OW_ATTACHMENTS" of the Alfresco BPM of the Alfresco WorkDesk.
I've tried many times with the bpm:workflowpagckage or bpm:package with no luck....help!
Edit:
function startWorkflow(name,docNode)
{
var workflow = actions.create("start-workflow");
workflow.parameters["bpm:workflowPackage"] = docNode;
workflow.parameters.workflowName = "activiti$AdHocactivitiTimer";
workflow.parameters["bpm:assignee"] = people.getPerson("admin");
workflow.parameters["bpm:workflowDescription"] = "test";
workflow.parameters["bpm:workflowPriority"] = "2";
workflow.parameters["bpm:sendEMailNotifications"] = true;
workflow.parameters["initiator"] = people.getPerson("admin");
var today = new Date();
var duedate = today.getDate() + 1;
workflow.parameters["bpm:workflowDueDate"] = duedate;
workflow.execute(document);
}
function main()
{
var docNode = search.findNode(document.nodeRef);
var name = document.name;
startWorkflow(name,docNode);
}
main();
thanks!
The bpm:package or bpm_package is not available before start.
So what happens you're document is added to bpm_package.
And in your workflow you can access bpm_package as a variable. And with bpm_package.addNode(doc); you can add nodes.
These nodes can be found through search/childbynamepath/xpath etc.
If you don't use the action the other way is:
var workflowAction = workflow.getDefinitionByName('activiti$AdHocactivitiTimer');
var package= workflow.createPackage();
package.addNode(document);
workflowAction.startWorkflow(package, parameters);
I am new with web application development. I have a code that lets you download a file after passing a basic authentication. It is working so far but I am not sure if this is the correct solution in achieving this solution. Or is there a drawback using this solution?
The "download" processing is being handled on a javascript using this code.
function downloadFile() {
var s = queryString("fn");
var f = "/web/et/" + s;
if (s.length > 1) {
window.open(f, "Download");
}
}
function queryString(parameter) {
var loc = location.search.substring(1, location.search.length);
var param_value = false;
var params = loc.split("&");
for (i = 0; i < params.length; i++) {
param_name = params[i].substring(0, params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=') + 1)
}
}
if (param_value) {
return param_value;
}
else {
return ""; //Here determine return if no parameter is found
}
}
#EDIT:
Sorry if I forgot to include the question, my question is, Is there a drawback on using this kind of solution? (pertains to downloading a file using javascript). Or is there a better solution for downloading a file aside from using a javascript?
I would handle any authentication on the server side b/c it is too easy to manipulate the (plainly) visible JS source. Not sure if that helps.
Example:
In the main page cliked on a button (NEW), the
page then will using Javascript to
open a new page in a new window by
calling redirectPage().
In the main page clicked on a button (EXIT),
then page then will call
confirmExit(), then
closeChildWindows() to closed all
popup new window before redirect to
another new page.
However, the JS variable
(childWindowHandles) will be always
reset if I refresh the main page,
and this cause the page unable to
close all other popup window before
relocated while EXIT button being
clicked
Does anyone know how can I solve this problem? By able to keep the JS variable (childWindowHandles) even the main page being refresh?
var childWindowHandles = new Array();
function redirectPage(url)
{
childWindowHandles[childWindowHandles.length] = window.open(url)
}
function confirmExit(url)
{
closeChildWindows()
window.location=url
}
function closeChildWindows()
{
for (var loop=0; loop<childWindowHandles.length; loop++)
{
if (!childWindowHandles[loop].closed)
{
childWindowHandles[loop].close();
}
}
}
You can use cookies to persist values...
Edit: You might find useful a simple object that I use:
Usage:
// Store a key/value for 1 day:
cookieManager.set('name', 'a value', 1);
// Retrieve a value associated to a key:
var value = cookieManager.get('name');
// Remove a key/value:
cookieManager.remove('name');
Implementation:
var cookieManager = {
set: function (name, value, expireDays) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + expireDays);
document.cookie = name + "=" + escape(value) +
((!expireDays) ? "" : ";expires="+expireDate.toGMTString());
},
get: function (key) {
var start,end;
if (document.cookie.length > 0) {
start = document.cookie.indexOf(key + "=");
if (start != -1) {
start = start + key.length + 1;
end = document.cookie.indexOf(";",start);
if (end == -1) {
end = document.cookie.length;
}
return unescape(document.cookie.substring(start,end));
}
}
return "";
},
remove: function (key) {
this.set(key, '', -1);
}
}
You can use cookies or window.name:) window.name to store session variables
Per this post here on SO, Firefox 3.5, Safari 4, and IE8 support HTML5 Storage.
Or use PersistJS which simplifies your access to whichever back-end storage mechanisms are available. (But cookie-less)
Use window.name
Positives:
it will live for the time of browser session - user closes window and it's gone
it won't put additional traffic on the wire like cookies do
it works even when cookies are disabled
at least 2MB space (Opera's limit is this low, other's have 32/64MB)
I also suggest you use javascript object for storing various values and serialize it using JSON and put that string into window.name.
Just make sure you don't persist any vulnerable data inside... For security reasons.
You can use sessionStorage.
Check this out:
html5_webstorage