How do I set this.location.href to a specific subdomain location - javascript

This is a version of Gatekeeper, I'm trying to get this to go to a subdomain of my website but it only goes to specific files on my main domain. Basically I enter 404 and it takes me to: http://mysite.com/404.html and I want it to go to: http://subdomain.mysite.com/404.html I'm kinda new to this but I think I need to change
if (password) { this.location.href = password + ".html"; }
to where the this.location.href doesn't read my current url but the url I specifically want.
Here is the full example code:
<HTML>
<HTML>
<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT language="JavaScript"><!--
/*********************************************************
GateKeeper v2.3 - by Joe Barta
http://www.pagetutor.com/keeper/
Permission is granted to freely use this script.
**********************************************************/
function GateKeeper() {
var password = prompt("Password required:", "");
if (password) { this.location.href = password + ".html"; }}
//--></SCRIPT>
</HEAD>
<BODY>
Click here for my secret page!
</BODY>
</HTML>
Any ideas or suggestions? Thanks in advance!

Related

How to change an Id on another page as it loads through JavaScript

I want for the user to click a button which leads to another page. Depending on what button the user clicks, the page content should look different despite being on the same page. A simplified example is below:
Starting page html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Click Here
Click Here
<script src="script.js"></script>
</body>
</html>
second-page.html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="content-id">*CONTENT SHOULD BE LOADED HERE BASED OFF BUTTON CLICKED*</p>
<script src="script.js"></script>
</body>
</html>
script.js code:
function changeContent(n) {
document.getElementById("content-id").innerHTML = n;
}
The above code does not work. I'm guessing the browser doesn't see the content-id on the first page and fails to change anything before loading the second page. Any way to reference the right id on the right page using JavaScript (no jQuery) when the new page is loaded?
Short answer: there are several approaches, the easier that comes to mind is to use localStorage if you're dealing with same origin pages
What you need is to have user information available across multiple pages. So, unlike sessionStorage, localStorage allows to store data and save it across browser sessions:
localStorage is similar to sessionStorage, except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.
To use it, consider adapting your javascript of first page:
function changeContent(n) {
localStorage.setItem('optionChosen', n);
}
Then retrieve it in the second page's javascript.
var opt = localStorage.getItem('optionChosen')
var content = document.querySelector('#content-id')
if (opt == null) console.log("Option null")
if (opt === 'Option One') content.innerText = "Foo"
if (opt === 'Option Two') content.innerText = "Bar"
Edited -
Added 3 working examples that can be copy and pasted.
Problem -
Display content on a new view based on the button clicked to get to that view.
Approach -
You can store the value of ID in the browser to help identify the content that should be displayed in many ways. I will show you three working examples.
Notes -
I am over complicating this a little to show you how you might make this work since I do not know the exact circumstances you are working with. You should be able to use this logic to refactor for your requirements. You will find the following 3 solutions below.
1. Using GET Params
Uses the GET params in the URL to help you track necessary changes in your view.
2. Using Session Storage
A page session lasts as long as the browser is open, and survives over page reloads and restores.
Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
Closing a tab/window ends the session and clears objects in sessionStorage.
3. Using Local Storage
The difference between localStorage and sessionStorage is the time the data persists. LocalStorage spans multiple windows and lasts beyond the current session.
The memory capacity may change by browser.
Similar to cookies, localStorage is not permanent. The data stored within it is specific to the user and their browser.
Solutions -
Working Examples - (Copy and paste any of the below solutions into an HTML file and they will work in your browser.)
Using GET Params
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
let currentURL = window.location.href.split("?")[0];
function appendParams(val) {
if (val === "a") {
window.location.assign(currentURL + "?id=a");
}
if (val === "b") {
window.location.assign(currentURL + "?id=b");
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="appendParams('a')">Click Here</button>
<button onclick="appendParams('b')">Click Here</button>
<p id="replace-id"></p>
</body>
</html>
<script type="text/javascript">
let url_str = window.location.href;
let url = new URL(url_str);
let search_params = url.searchParams;
let id = search_params.get("id");
document.getElementById("replace-id").id = id;
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("a").innerHTML = ContentOne;
}
if (id === "b") {
document.getElementById("b").innerHTML = ContentTwo;
}
</script>
Using Session Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
sessionStorage.setItem("id", "default");
function addSessionStorage(val) {
sessionStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = sessionStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addSessionStorage('a')">Click Here</button>
<button onclick="addSessionStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>
Using Local Storage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript">
localStorage.setItem("id", "default");
function addLocalStorage(val) {
localStorage.setItem("id", val);
updateContent();
}
function updateContent() {
let id = localStorage.getItem("id");
let ContentOne = "Some text if id is A";
let ContentTwo = "Some text if id is B";
if (id === "a") {
document.getElementById("replace-content").innerHTML =
ContentOne;
}
if (id === "b") {
document.getElementById("replace-content").innerHTML =
ContentTwo;
}
}
</script>
<title>Working Example</title>
</head>
<body>
<button onclick="addLocalStorage('a')">Click Here</button>
<button onclick="addLocalStorage('b')">Click Here</button>
<p id="replace-content">Default Content</p>
</body>
</html>

What's wrong with this code? It's doing nothing

<HTML>
<HEAD>
<script>
$(function(){
$(window).on('hashchange', function() {
var hash = location.hash.replace( /^#/, '' );
document.title = 'example ' + hash;
});
$(window).trigger('hashchange');
});
</script>
<TITLE>example</TITLE>
</HEAD>
<BODY>
</body>
</HTML>
Let's say the <title> of example.com is example
This code should automatically update the page title for example.com/#city1 to example city1 and example.com/#city2 to example city2 and so on.
I have only an index.html file and I don't want to add php file to my html file.
As said in the comments you need to add the jQuery library to your page using :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
Then your code should work as expected.

Google+ API doesnt return access_token Javascript

We have an application that relies upon Google to authenticate its users against our google apps account and then do some serverside verification and group lookups.
Recently google changed the name of the object that held the access_token variable which we require to authenticate. In the docs (https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile) it says that access_token is available from the getAuthResponse() method, however when i use this it comes back as undefined. Inspecting the object after console.log() reveals all the other fields mentioned except access_token. I'm worried that Google will change the object again in the future and leave us without our application.
Here is the code.
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<meta name="google-signin-client_id" content="XXX.apps.googleusercontent.com">
<script>
//This happens after the user has authenticated with Google and has been passed
//back to the page
function onSignIn(googleUser) {
//Check to see whether the user is trying to sign out.
if (window.location.href.indexOf("signOut=1") !== -1) {
//Sign them out of the application.
signOut();
//redirect them to the same page, without the signOut query string so they can log back in if want
window.location.href='googlesigninform.html'
return false;
}
//Grab the token, access token and email.
var _id = googleUser.getAuthResponse().id_token; //This works
var _accessToken = googleUser.Ka.access_token; //This works but changed from googleUser.B.access_token
var profile = googleUser.getBasicProfile(); //Works
console.log(googleUser.access_token); //Undefined
console.log(googleUser.getAuthResponse().access_token);//Undefined
//Make a post request to the API
makePostRequest(_id, _accessToken, profile.getEmail());
}
What is the correct way to access the access_token variable?
If you need to use access token you are using the wrong type of google signin flow.
You should follow this page: https://developers.google.com/identity/sign-in/web/server-side-flow
What you did implement is google Sign-In to identify users (https://developers.google.com/identity/sign-in/web/)
Which only provides a unique id per user because it is meant to authenticate the user for your own service and not to give an access token to use for other Google services later on.
I believe your problem is that your application is lacking the necessary google-signin-scope.
To answer your question i created an app from the ground using the Google Developer Console. The application is very simple like the one this this tutorial.
The entire application consists of a simple HTML that loads the google API and has a callback called onSignIn (like yours).
Here's the entide code of the application:
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="PLACE_YOUR_ID_HERE.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
var response = googleUser.getAuthResponse(),
idToken = response['id_token'],
accessToken = response['access_token'];
console.dir('id token: ' + idToken);
console.dir('access token: ' + accessToken);
}
</script>
</body>
</html>
As you can see, the difference between my app and yours is that yours is lacking the first META attribute.
Well i have a hack work around that gets the access_token from the variable.
function findAccessToken(googleUser) {
var returnValue;
Object.getOwnPropertyNames(googleUser).forEach(function (val, idx, array) {
console.log(val + ' -> ' + googleUser[val]);
Object.getOwnPropertyNames(googleUser[val]).forEach(function (vals, idxs, arrays) {
if (vals === "access_token") {
console.log("true");
returnValue = googleUser[val][vals];
}
});
});
return returnValue;
}
Surely this can't be the most elegant solution. If someone could point in the righter direction that would be good.
Here is the code for sign in using google.
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log("Name: " + profile.getName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
</body>
</html>
Try this
var _access_token = GoogleUser.getAuthResponse().access_token

how to create contact in iphone using phonegap

I am new to iPhone development and phonegap also. Now i want to create contact in iPhone using phonegap. I got the link to create contact in iPhone with coding. But there one HTML coding with JavaScript. But when i run the coding the simulator and device show's only the HTML tag contents.
I followed this below link only:
"http://docs.phonegap.com/en/2.0.0/cordova_contacts_contacts.md.html#Contacts"
I have attach the coding and Screen Short:
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.note = "This contact has a note.";
navigator.contacts.save(myContact); //HERE
console.log("The contact, " + myContact.displayName + ", note: " + myContact.note);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contact</p>
</body>
</html>
Screen Short:
Please help me to solve the issue. I have followed all the instruction from that above link. But I didn't get the solution. Thanks in advance.
You need to save your contact.
The documentation states :
contacts.create is a synchronous function that returns a new Contact object.
This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method.
function onDeviceReady() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.note = "This contact has a note.";
navigator.contacts.save(myContact); //HERE
console.log("The contact, " + myContact.displayName + ", note: " + myContact.note);
}
var myContact = navigator.contacts.create({"displayName": "Test User"});
Full Example
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
try {
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; //specify both to support all devices
// populate some fields
var name = new ContactName();
name.givenName = "Jane";
name.familyName = "Doe";
contact.name = name;
// save to device
contact.save(function(){
alert("Save Success");
},function(){
alert("Error...");
});
} catch(_err) {
alert(_err)
}
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Create Contact</p>
</body>
</html>
OR You can find more option for contact api.
I think you have not read document. i have also edited my answers please check once again.
Description :
contacts.create is a synchronous function that returns a new Contact object.
This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method.
http://docs.phonegap.com/en/1.0.0/phonegap_contacts_contacts.md.html#contacts.create

Displaying like / unlike pages in facebook

I have been trying to make facebook page that will display different content depending on the Like / Unlike. I found the code below on this site which works to a certain extent however not in Chrome Browser - I also get a nasty pop-up that is XD Proxy. In firefox this pops up and then goes away before working perfectly.
Any help would be greatly appreciated.
Index.html (displayed in the iFrame)
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<title>BASE</title>
<link rel='stylesheet' href='css/style.css' />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>
<script src='js/example.js'></script>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '114317821995273',
status : true,
cookie : true,
xfbml : true
});
</script>
<div id="container_notlike">
YOU DONT LIKE
</div>
<div id="container_like">
YOU LIKE
</div>
</body>
</html>
Javascript is:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "187015391355550"; //Test Page
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
});
Many thanks in advance to anyone that can help. And thanks to the previous poster that has got me this far.
Your fql query needs a space after the page_id.
It should read:
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+" and uid="+user_id;

Categories