what is wrong with this JS cookie Script? - javascript

I have a code that has no syntax errors (Dreamweaver) but the Chrome JS console is saying that ExistsCookie is undefined. The cookie was in the cookie list for that site but the page is not redirecting. What am I doing wrong? NOTE: I know people can turn cookies off.
var cname = "voicevote"
var data ="1";
function CheckForCookie()
{
if( ExistsCookie(cname) )
{
window.location.replace("cookie.htm")
}
}

Most likely, ExistsCookie is a function that you haven't included in your script- if this was taken from a tutorial on some other website, look there- there may be a function on that page which you forgot to include in your code.
EDIT: After some googling, it looks like this is what you need:
function ExistsCookie(name)
{
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
var aCrumb = aCookie[i].split("=");
if (name == aCrumb[0])
return true;
}
return false;
}
(Source, which appears to match original question)

Related

How to create a bookmarklet with multiple functions

I'm new to creating JavaScript bookmarklets but have got a certain way in solving my problems but have got stuck on one final bit.
Basically, I want to create a bookmarklet that will replace text in 2 places in the URL - the subdomain and the URI.
I have managed to do this for the first part:
(function() {
window.location = window.location
.toString()
.replace(/^https:\/\/www\./, "https://edit.");
})();
Next, I need to grab some metadata (cab-id) from the page. I've managed to do this an print it to the console:
function getCabID() {
var metas = document.getElementsByTagName("meta");
for (var i = 0; i < metas.length; i++) {
if (metas[i].getAttribute("name") == "cab-id") {
return metas[i].getAttribute("content");
}
}
return "";
}
console.log(getCabID());
The next thing I need to do is replace the end of the url (everything from "www.xxxxxx.org.uk/*" with the following:
/EPiServer/CMS/Home#context=epi.cms.contentdata:///
I can't figure out how to do this, I'm really struggling. I've come up with the following but it's not working:
(function() {
var url=window.location.href;
stringUrl=String(url);
stringUrl=stringUrl.replace(/^https:\/\/www.xxxxxx.org.uk\/, "https://edit.xxxxxx.org.uk/EPiServer/CMS/Home#context=epi.cms.contentdata:///");
document.location=stringUrl;
})();
I'll also need to pop the cab-id at the end of all this directly after ///.
Sorry for the long question but what I need to do is:
Make the 3rd one actually work!
Combine the 3 functions
Any tips would be massively appreciated :D
As I understood your question, the following bookmarklet probably allows to combine the 2nd and 3rd steps:
javascript:(function() {
window.location.href = "https://edit.xxxxxx.org.uk/EPiServer/CMS/Home#context=epi.cms.contentdata:///" + getCabID();
function getCabID() {
var metas = document.getElementsByTagName("meta");
for (var i = 0; i < metas.length; i++) {
if (metas[i].getAttribute("name") == "cab-id") {
return metas[i].getAttribute("content");
}
}
return "";
}
})();

Retrieving double redirects through MediaWiki API

I want to write a script to resolve double redirects automatically after a page move. Here is what I have started with:
(function () {
var api = new mw.Api();
api.get( {
action: 'query',
list: 'backlinks',
blpageid: mw.config.get('wgArticleId'),
blfilterredir: 'redirects',
blredirect: true,
bllimit: 500
} ).done( function (data) {
var fixed = 0;
redirects = data.query.backlinks;
for (var i=0; i<redirects.length; i++) {
var doubles = redirects[i].redirlinks;
if (doubles === undefined) {
continue;
}
for (var j=0; j<doubles.length; j++) {
console.log(doubles[j]);
fixed ++;
}
}
mw.notify(fixed);
} );
})();
The problem is that if I run this function on a page like Wikipedia:Blocking policy the script returns some pages that are not actually double-redirects, but merely redirects containing links to it.
I can check each of them to see where they are actually pointing to, but isn't there any better way? i.e. a simple method to retrieve double redirects only.
If you are happy with using python and the pywikibot framework there is https://m.mediawiki.org/wiki/Manual:Pywikibot/redirect.py which should do what you want.
Otherwise you might want to work with the output of Special:DoubleRedirects.

Strange behavior checking for Web Storage availability

Here's my code:
if(typeof(Storage)!==undefined) {
// Web storage support
if(localStorage.hashes != "") {
var hashes = jQuery.parseJSON(localStorage.hashes);
for (var i = 0; i < hashes.length; i++) {
// Do stuff here
}
}
else {
var hashes = [];
}
}
else {
// No web storage support
}
I don't really know what's going on, but when I try to load the page with this code from a device for the first time, the rest of my code doesn't work the way it should. However, if I comment it out then visit the page for the first time everything works. I can then uncomment it, reload the page, and everything will continue to work. This is really the best I can describe what's happening.
I believe you could have done a little more debugging before posting this.
Have you tried logging/ adding checks (to see where exactly this issue is coming from and what the error is) ?
But since we're here, here are my tips for localStorage :
Use modernizr (http://modernizr.com/)
if(Modernizr.localstorage){ /* Your code */}
Make some generic get and set functions
function get(key) {
if(Modernizr.localstorage) {
if(localStorage[key] != null) {
return localStorage[key];
}
}
return null;
}
function set(key, value) {
if(Modernizr.localstorage) {
localStorage[key] = value;
}
return null;
}
This is pretty rough, you tweek it to make it safer and respond to your needs
Put try/catch inside your get and set functions, you don't want write operations to impact your program
I figured it out! So in the above code I check if they had localStorage available, and if they do, I just assume that they have some hashes stored in there. This obviously creates a problem on their first visit as they wouldn't have any hashes saved yet. So I have to check if they have any, if they do, then do the for loop, otherwise just set it to an empty array. Like so!
if(typeof(Storage) !== "undefined") {
// Web storage support
if(localStorage.hashes != "") {
hashes = JSON.parse(localStorage.getItem("hashes"));
if(hashes) {
for (var i = 0; i < hashes.length; i++) {
// Do Stuff
}
} else {
hashes = [];
}
}
else {
hashes = [];
}
}
else {
// No web storage support
hashes = [];
}
Thanks to jbabey for tips on cleaning up my code some!

How do I access the querystring using javascript?

I have a querystring which looks like this page3.html?redesigndata=value which it appears if its redirected from page1.html and page3.html?new=yes or no when redirected from page2.html. Here is the code I'm using to find out what the querystring is and do some functions on page3.html
var locurl = window.location.search;
if (locurl.substring(0, 13) === '?redesigndata') {
alert("redesign!");
} else if (locurl.substring(0, 4) === '?new') {
visit = locurl.substring(5);
alert("somthing!");
if (visit === 'yes') {
alert("first!");
} else if (visit === 'no') {
alert("again!");
}
}
but I don't get any alerts when I try this script and I cant find out what's wrong with it.
Try using this function
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
Check like this
if(getQueryString()["redesigndata"] != "")
There is nothing wrong with the code you posted. If the alerts never fire, it's because the conditions are never met. Once a query string is added to the URL that DOES match one of those you listed in your code, the alert does fire.
Also, beware you're (seemingly) creating global vars.
The script works on my box. Please put this script inside script tags

Posting data into JavaScript from an URL

I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();

Categories