Get param value after hash in URL in vanilla JS - javascript

I know this is probably extremely simple, but I can't seem to figure it out or find the answer I'm looking for. I'm using Instagram's API to allow user's to login and see their feed. This is done on the client side with Javascript. After authorizing my app, the browser sends back an access token in the url like so: www.example.com/#access_token=12345679.
What's the simpest vanilla JS to get the raw number of the access token? I've tried location.hash but that returns both the key and value like so: acess_token=123456789
Any help appreciated.

Assuming the hash pattern is consistent, you can get the access_token value with the following code:
var hash = window.location.hash;
var accessToken = hash.split('=')[1];

Just split with '=' on the returned key value pair
var token = obj.split('=')[1] ;

Related

How do I append a query parameter to my URL using Javascript?

I am building a web app and I am using Firebase to store my user's data in Cloud Firestore. There is a page on my web app that allows users to view their documents from Cloud Firestore. I would like to add a query parameter to the end of my URL on view.html so I can take that query parameter value and use it to search for a document.
I have been searching online to find possible solutions. So far I have come across a few videos on the topic, but they haven't been going into the depth I have been needing. For example, this video shows how to add and get query parameters from a URL, but it only shows how to log those changes in the console. How would I make that my URL?
I've also be browsing Stackoverflow for solutions. This Stackoverflow post asks a similar question, however, many of the solutions in the answers causes view.html to reload on a loop. Why would this be, and if this is a possible solution, how would I stop this from happening.
How would I go about appending and fetching URL query parameters in Javascript?
You say you want to do this in javascript, so I assume the page itself is building/modifying a link to either place on the page or go to directly via javascript.
In javascript in the browser there is the URL object, which can build and decompose URLs
let thisPage = new URL(window.location.href);
let thatPage = new URL("https://that.example.com/path/page");
In any case, once you have a URL object you can access the parts of it to read and set the values.
Adding a query parameter uses the searchParams attribute of the URL, where you can add parameters with the .append method — and you don't have to worry about managing the ? and & … the method takes care of that for you.
thisPage.searchParams.append('yourKey', 'someValue');
This demonstrates it live on this page, adding search parameters and displaying the URL at each step:
let here = new URL(window.location.href);
console.log(here);
here.searchParams.append('firstKey', 'theValue');
console.log(here);
here.searchParams.append('key2', 'another');
console.log(here);
I have solved this issue in the simplest way. It slipped my mind that I could link to view.html by adding the search parameter to the URL. Here's what I did:
On index.html where I link to view.html, I created the function openViewer();. I added the parameter to the end of URL href.
function openViewer() {
window.location.href = `view.html?id={docId}`;
}
Then on view.html, I got the parameter using URLSearchParameters like so:
const thisPage = new URL(window.location.href);
var id = thisPage.searchParams.get('id');
console.log(id)
The new URL of the page is now "www.mysite.com/view.html?id=mydocid".
You can try to push state as so in the actual view.html
<script>
const thisPage = new URL(window.location.href);
window.history.pushState("id","id",thisPage);
</script>

How to pass wildcard in vue js post request?

How I can get the current wildcard id and pass it to my $http.post route in vue?
Once I created a quiz information it will return a page with a new url
http://localhost:8000/question/index/quiz/3
Then when I want to do a post route with a name
Route::post('question/store/quiz/{quiz}');
Here is my Vue http request post method
this.$http.post('/question/store/'+ , input).then((response) => {
What will be id that I can pass after the + sign?
Well this is pretty hacky, but it'll work if your URLs are always going to be formatted like that. so what I'm doing here is using vanilla JS to get the URL pathname, parse the string by the / and turn it into an array, then grab the last index.
var locationString = location.pathname
var locationArray = locationString.split('/')
var quizId = locationArray[locationArray.length - 1];
The quizId variable is the wildcard you're looking for
You should note that this is going to break if you ever have any query parameters, such as a URL looking like: /index/quiz/3?v=2842

Servlet calling from window.showModalDialog(...)

I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks

404 retrieving Twitter followers using JQuery getJSON

I'm just starting to use the Twitter API to retrieve data using jQuery. I've used the API ok to retrieve information about a single user e.g. https://twitter.com/users/show/codinghorror.json
When I try to retrieve all the users that a given user is following, I'm using the same retrieval pattern but am getting a 404 error (it looks like my callback isn't receiving the json object properly, but appending it to the URL somehow)
I'm using the following code:
getTwitterUserFriends: function() {
var user = 'codinghorror';
var url = 'http://api.twitter.com/1/friends/ids.json?screen_name='+user+'?callback=?';
$.getJSON(url, function(data) {
alert('call succeeded' + data.ids);
});
},
In chrome, the console shows the following error:
GET https://api.twitter.com/1/friends/ids.json?screen_name=codinghorror?callback=jQuery15201747908447869122_1324917568956&_=1324917580929 404 (Not Found)
However if I browse to the URL directly https://api.twitter.com/1/friends/ids.json?screen_name=codinghorror then I can see the results object being returned.
I assume I'm doing something simple wrong with my callback, but can't see what it is, as the approach I've used above has worked for other API calls, so any help would be much appreciated!
Your URL syntax is incorrect. The "callback" parameter should be separated by "&", not "?".
var url = 'http://api.twitter.com/1/friends/ids.json?&screen_name='+user+'&callback=?';
You should probably URL-encode the username too:
var url = 'http://api.twitter.com/1/friends/ids.json?&screen_name=' +
escapeURIComponent(user) +
'&callback=?';
Also I'm not sure why you've got a "&" before the "screen_name" parameter.

Obtain forwarded URL from a source URL?

What is a good way to obtain the end URL if given a URL that is being forwarded to another URL?
For example, if I had the shortened URL: http://bit.ly/900913, what is a good way to determine that this ultimately forwards to http://www.google.com?
I'm using javascript. I'm unsure if this can be done somehow using jQuery (doubtful since the end URL probably isn't returning jsonp content) or if there is some kind of web service that I can use.
Thanks!
For bit.ly specifically, you can use the bit.ly API to make a JSONP call using JavaScript to expand the bit.ly URL(s) in question.
Specifically, you'd use the v3/expand call.
Pseudo-code:
var bitlyurl = "http://bit.ly/900913";
$.getJSON("http://api.bitly.com/v3/expand?shortUrl=" + encodeURIComponent(bitlyurl)+"&apikey=...&callback=?", function( bitlydata ){
var endurl = bitlydata.data.expand[0] //looks like this is where the end URL would point
});
Alternately, you could follow the URL on your own server, and use AJAX to check it's values.
So, you'd pass it a URL ($.get("/follow?url="+bitlyurl,function(data){var endurl = data.Location;});, and make a HEAD call to the URL to see where the Location points.
Here's the basics of how you'd do it in PHP:
<?php
$headers = get_headers($_GET["url"],1);
echo json_encode($headers);
?>
Just for fun, I implemented a live end-point on App Engine to check where a URL points. Feel free to use it! The base URL is followtheredirect.appspot.com, and it requires a url parameter and a callback parameter, and returns a location key on the resulting object, when successful.
Sample code:
$.getJSON("http://followtheredirect.appspot.com/?url="+encodeURIComponent('http://bitly.com/hhN7Ol')+"&callback=?",function(data){
var location = data.location;
});
Let me know if you find any bugs :) it might be a bit messy...
Bitly provides a preview service. If you visit http://bit.ly/900913- (notice the hyphen at the end), you'll get a response with the full URL.

Categories