I am new to web scripting. Not at all expert in HTML advanced handling either. I have been working to get a response from API using Javascript and HTML. I get the response back from API.
However, I am not sure how I can display the data received in HTML. For example, I see that upon request, the API redirects me to my test page as desired - http://localhost/test.html
I want to display all parameters received from the API in a table in this HTML page. How can I achieve this? Here is the URL response I receive from API -
https://localhost/test.html?state=myState&scope=CustomApi&access_token=somerandomtokenjibberjabbergoeshere&expires_in=5184000&resource_server_base_uri=https%3a%2f%2fapi-b2.someapi.com%2fsomeAPI%2f&token_type=bearer
Here is my incomplete HTML -
<!DOCTYPE html>
<html>
<head>
<title>
Data received from API request
</title>
</head>
<body>
<div class="container">
<div id="result" style="color:red"></div>
</div>
</body>
</html>
Thanks.
For anyone else wondering, here is what I used
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
And then I called the variables as below
var token = getParameterByName('access_token'); // "value1"
var state = getParameterByName('state'); // "value2"
Related
We have an embedded script running on the page of one our clients. We received a report from them that the query params we send to that page are not properly guarded against XSS injection.
When I try a url like:
https://www.clientsite.com?somekey=%3Csvg%20onload%3Dalert(document.cookie)%3E
on their site, I indeed get the alert panel displaying the cookies.
But when I run our script locally, I cannot reproduce this injection. The alert panel never shows up, no matter what I put in the query param's value.
A very simplified version of the script is:
<html lang="en">
<head>
<meta charset="utf-8">
<title>XSS test</title>
</head>
<body>
<div id="content"></div>
<script>
(function() {
var url = window.location.href
var someKey = 'somekey'
var regexS = "[\\?&]"+someKey+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
var parentElement = document.querySelector('#content');
var widget = document.createElement('div');
// var svgInjection = '<svg onload=alert("alert!!")>'
// var svgEncodedInjection = '%3Csvg%20onload%3Dalert("alert!!")%3E'
widget.innerHTML = '<div>' + results[1] + '</div>';
return parentElement.insertBefore(widget, parentElement.firstChild);
})()
</script>
</body>
</html>
I don't understand how an identical script, receiving identical query params, shows an alert panel on the client's site, and nothing when I run it locally. Any thoughts?
I have had an issue with getting the google scripts page to redirect back towards my custom URL. The script currently executes but I cant get it to redirect back to its previous page after it is finished executing.
Heres the script.gs code:
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
// shorter name for form data
var mailData = e.parameters;
var name= String(mailData.name);
var message= String(mailData.message);
var email= String(mailData.email);
var all= ("Name: "+name+"\nReply address: "+email+"\nMessage: "+message);
// determine recepient of the email
// if you have your email uncommented above, it uses that `TO_ADDRESS`
// otherwise, it defaults to the email provided by the form's data attribute
var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
MailApp.sendEmail({
to: String(sendEmailTo),
subject: String(mailData.subject),
replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
body: String(all)
});
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="2;url=xxxxxxxxxx.com" />
<base target="_top">
</head>
<body>
Click here to go back.
</body>
</html>
What would be the best way to make the script open the index.html page so I could easily redirect back to the custom URL?
Here's a working example of redirecting after processing a POST request.
Code.gs
var REDIRECT_URL = "http://www.stackoverflow.com";
function doPost(e) {
Logger.log("POST request");
Logger.log(e)
return redirect();
}
function doGet() {
Logger.log("GET request");
var template = HtmlService.createTemplateFromFile("form");
template.url = ScriptApp.getService().getUrl();
return template.evaluate();
}
function redirect() {
return HtmlService.createHtmlOutput(
"<script>window.top.location.href=\"" + REDIRECT_URL + "\";</script>"
);
}
form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form action="<?= url ?>" method="post">
<input type="text" name="test_field" value="test data">
<button type="submit">Submit form</button>
</form>
</body>
</html>
Usage
When I visit the published web app (i.e. using a GET request), I'm presented with the simple form.
Submitting that form (i.e. using a POST request), I'm immediately redirected to http://www.stackoverflow.com.
This output is captured in the script log:
[18-06-19 10:39:04:731 PDT] POST request
[18-06-19 10:39:04:732 PDT] {parameter={test_field=test data}, contextPath=, contentLength=20, queryString=, parameters={test_field=[test data]}, postData=FileUpload}
Regarding your code sample, you have:
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
That doesn't make sense as you're not doing anything with the results of doGet(). In order to make the doGet() call useful, replace the above with the following:
return doGet();
The following is a JavaScript file that searches through YouTube video data using its API. Down at the bottom you'll see the onSearchResponse() function, which calls showResponse(), which in turn displays the search results.
As this code from Codecademy stands, a HUGE amount of information gets printed relating to my search term.
Instead of all that, can I simply display a hyperlink using the title and videoId attributes? How would I go about altering responseString in showResponse() to build that link? Thank you!
// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See link to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'clapton'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
console.log(response);
}
Here is the corresponding HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylesheets/styles.css">
<meta charset="UTF-8">
<title>My YouTube API Demo</title>
</head>
<body>
<section>
<div id="response"></div>
</section>
<script src="javascripts/search-2.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>
Your advice is much appreciated!
I think it might be what you are exactly trying to do.
function showResponse(response) {
var html = response.items.map(itemToHtml);
document.getElementById('response').innerHTML += html;
}
function itemToHtml(item) {
var title = item.snippet.title;
var vid = item.id.videoId;
return generateHyperlink(title, vid);
}
function generateHyperlink(title, vid) {
return '' + title + '<br/>';
}
This code show up links named title having YouTube video link using videoId.
I'm creating a script like twitter in which user just provide an id and all his/her tweets get loaded on site where the script inserted.
What I've done is
User should copy this code to load my widget
<a class="getStarted" data-getStartedID="123456789">Get Started App ID</a>
<script>
!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src=p+"://localhost/practices/js_practice/siteOpen.js";
fjs.parentNode.insertBefore(js,fjs);
}}(document,"script","getStarted-C");
My siteOpen.js is as below :
!function(d){
var a = d.getElementsByClassName('getStarted');
var x = document.getElementsByClassName("getStarted")[0].getAttribute("data-getStartedID");
var r = new XMLHttpRequest();
var appID = x;
r.open("POST", "openwebIndex.php", true);
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", appID.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
if(r.responseText.trim()==1){
return '<p>output to be draw on where script is pasted</p>';
if(console)console.info('Valid appID');
}
};
r.send('appID='+appID);
}(document);
i don't know what to do to send the response and load/draw my widget on user's website.
My response will be in html elements.
Please suggest me what should i do. I just stuck at this point.
EDIT
I'm getting object HTMLScriptElement when I alert js variable.
Just trying adding the html code in the body tag.
users html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
<script src="widget.js"></script>
Your widget.js
// var appId = d.getElementsByClassName('getStarted');
// process the app id and make the output here
var output = "<div>This is the content of the widget</div>";
document.body.innerHTML += output;
This will show the content in the users html file. If you have cross domain issue, use JSONP for resolving that.
I have a script here, copied pretty much directly off this. Why doesn't the code, listed below, return anything?
ajax.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cross-Domain Ajax Demo</title>
</head>
<body>
<div id="container">
<form>
<p><label>Type a URL:</label><input type="text" name="sitename" id="sitename"/></p>
<p><input type="submit" name="submit" id="submit" value="Make Cross Domain Ajax request"</p>
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="cross-domain-requests.js"></script>
<script type="text/javascript">
$('form').submit(function() {
var path = "www.google.com";
requestCrossDomain(path, function(results) {
$('#container').html(results);
});
return false;
});
</script>
</body>
</html>
cross-domain-requests.js:
// Accepts a URL and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no URL was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided URL, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
(I'm relatively new to scripting and Ajax, so I apologise in advance if I do anything stupid.)
Try changing the callback in var yql to callback=? and the select statement to 'from xml' like this:
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';