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.
Related
I have almost the same problem that in thread "Adobe PDF Embed API can not change the pdf" and "How to use a variable in Adobe's pdf embed API as URL-value?". which both were addressed by Mr Raymond Camden. The only difference is that I am trying to pass an url to location:url from Flask. Here's the code:
if(window.AdobeDC) displayPDF(urldata);
else document.addEventListener("adobe_dc_view_sdk.ready",
() => displayPDF(urldata));
function displayPDF(urldata) {
document.writeln(urldata[0]);
document.writeln(urldata[1]);
var myURL = urldata[0];
var myFileName = urldata[1];
adobeDCView.previewFile({
content: {
location: {
url: myURL,
},
},
metaData: {
fileName: myFileName
}
}, viewerConfig);
}
Note that I am using Mr Camden trick for dealing with
well-seasoned chicken and nice fresh eggs
.
I can get my 2 parameters going to the html file and to the js file. They are both writelined on the page from the displayPDF(urldata) function. Unfortunately they don't make it to content:location:url and metadata:filename. If I do hardcode these two parameters with existing PDF url and filename I get the result I want to obtain.
What am I doing wrong?
Thanks to anybody who could give me a clue.
All the best,
Pierre-Emmanuel FEGA
zepef#hotmail.com
I've found an answer to my own question. I have posted it on Adobe Community forum as well because "Passing value from external function to document function" because both responses from Shubhanshu Dixit and Raymond Camden have been of great help to me.
My goal was to open a PDF file coming from Azure Blob Storage to use it in an Azure Web App. The app is in Flask. Here's how I've done it and it works great on Azure as well as locally:
FLASK ROUTE
#app.route("/document", methods=['GET', 'POST'])
def document():
# Microsoft blob storage SAS token creation for accessing PDF file in blob storage
blob = get_blob_sas(BLOB_NAME_PATH, STORAGE_ACCOUNT_KEY, BLOB_CONTAINER_NAME, document_to_retrieve)
blob_url = 'https://'+BLOB_NAME_PATH+'.blob.core.windows.net/'+BLOB_CONTAINER_NAME+'/'+document_to_retrieve+'?'+blob
# URL and Filename parameters to send to Adobe Embed API
urldata = [blob_url, document_to_retrieve]
return render_template('view.html', title='SYSTRA Semantic Selected Document', urldata=urldata)
HTML PAGE
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1"/>
<script type="text/javascript" src="{{ url_for('static', filename='view.js') }}"></script>
<script type="text/javascript">
varPDF = previewFile({{urldata|tojson}})
</script>
</head>
<body style="margin: 0px">
<div id="adobe-dc-view"></div>
<script type="text/javascript" src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
</body>
</html>
JAVASCRIPT FUNCTIONS
function previewFile(urldata) {
var myURL = urldata[0];
var myFileName = urldata[1];
if(window.AdobeDC) displayPDF(myURL, myFileName);
else document.addEventListener("adobe_dc_view_sdk.ready",
() => displayPDF(myURL, myFileName));
}
function displayPDF(myURL, myFileName) {
document.write('displayPDF');
const viewerConfig = {
embedMode: "FULL_WINDOW",
defaultViewMode: "FIT_PAGE",
showLeftHandPanel: true,
showAnnotationTools: true,
showDownloadPDF: true,
showPrintPDF: true,
showPageControls: true,
showDisabledSaveButton: true,
downloadWithCredentials: true
};
var adobeDCView = new AdobeDC.View({
clientId: '<CLIENT_ID_KEY_HERE',
divId: "adobe-dc-view"
});
adobeDCView.previewFile({
content: {
location: {
url: myURL,
},
},
metaData: {
fileName: myFileName
}
}, viewerConfig);
}
I hope this helps.
All the best,
Pierre-Emmanuel
I writing a html page run from file:// (not use webserver)
I want display a message [Loading.....] in div while Page processing create a data
This is my code demo:
before get data i set:
$("#msg").html("Loading.....");
and after get data i set:
$("#msg").html("Done!");
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script type="text/javascript">
function search() {
$("#msg").html("Loading.....");
getData();
$("#msg").html("Done!");
}
function getData() {
var html = "";
for (var i = 0; i < 200000; i++) {
html += i + "<br>";
}
$("#data").html(html);
}
</script>
</head>
<body>
<input type="button" id="btnSearch" value="Search" onclick="search(); return false;" />
<div id="msg">Message</div>
<div id="data"></div>
</body>
</html >
How can show message while processing a javascript function?
i try use ajax:
function search() {
$("#msg").html("Loading.....");
$.ajax({
success: function () {
getData();
$("#msg").html("Done!");
}
});
}
But it occuring error:
Access to XMLHttpRequest at 'file:///C:/Users/dt/Desktop/HTMLPage1.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Actually, there are two problems with this code.
1. Trying to make AJAX request over file:// protocol
That's where you get the error from. Doing this is incorrect because of security of the users.
Imagine, that you visit a random website on the Internet, and it can see all of your files on your computer, without even asking for permission or letting you know what it does. In that case, those who use the Internet could say goodbye to private life!
So, instead:
If this file will be on your server, and you're just testing, then do it on a localhost server.
If you want to let the user grant access to one of his/her files, use a filepicker (<input type="file">).
If you want to access users' files without permission, then... look for alternative solutions (web pages cannot do this).
2. Synchronous data processing
Once you've somehow solved to get the files, your example will work. But you'll be unable to update the display during processing. That's why your first example doesn't work.
It will also don't let other rendering, or asynchronous JS code to run. Usually, this isn't a problem, as long as your code doesn't take long time to execute.
But if it does, you'll need to let some scheduled code to execute, during the processing.
You have 2 options:
Use a Web Worker to do heavy synchronous operations without freezing the site
//your HTML file
<script>
async function search() {
$("#msg").html("Loading.....");
await getData();
$("#msg").html("Done!");
}
function getData() {
return new Promise((rs,rj) => {
const worker = new Worker('./worker.js')
worker.onmessage = rs
worker.onerror = rj
})
.then(data => $("#data").html(data));
}
</script>
//worker.js
var html = "";
for (var i = 0; i < 20000; i++) {
html += i + "<br>";
}
self.postMessage(html)
Put setTimeout(..., 0) in your processing code to make it asynchronous and the site usable while processing
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script type="text/javascript">
async function search() {
$("#msg").html("Loading.....");
await getData();
$("#msg").html("Done!");
}
async function getData() {
var html = "";
for (var i = 0; i < 20000; i++) {
html += i + "<br>";
if(i % 10 === 0)
//On every 10th iteration, wait some...
await new Promise(rs => setTimeout(rs, 0))
}
$("#data").html(html);
}
</script>
</head>
<body>
<input type="button" id="btnSearch" value="Search" onclick="search(); return false;" />
<div id="msg">Message</div>
<div id="data"></div>
</body>
</html >
Good question!
AJAX and XMLHTTP requests send messages over HTTP Protocol. HTTP is a protocol for sending messages over the internet. You must use a webserver, or at least call to localhost, in order to make a HTTP request from your clientside code.
If you really want to just show a "loading" message, sending your request to localhost will at least allow you to "SEND" your HTTP request. Just know that your request will always fail unless you set up a webserver on localhost to answer it. You could write your "Done!" in an ajax fail function in that case:
$.ajax({
success: function () {
getData();
$("#msg").html("This will never show up until you set up a webserver that you called from localhost");
}
fail: function () {
getData();
$("#msg").html("Done! (This is showing because you called from localhost)!");
}
});
This is a follow-up question of this one.
Goal is to use some user input that is converted to a HTML document that should be displayed in a new tab (that's answered in the link above).
Problem is, however, that - if the HTML document contains <script> tags - those are not executed when this HTML string is passed as JSON. Below I use a simple string:
'<!DOCTYPE html><title>External html</title><div>Externally created</div><script>alert("WORKING");</script>'
This is a minimal example to illustrate the problem (you will see this in your browser when you load the HTML from below):
When I click on the button, the new tab is opened but the script is not executed i.e. there is no alert shown. By clicking on the alert link, the html string is loaded directly and the alert is shown correctly.
My question is, how to postprocess the HTML string that is returned from .getJSON to execute the script correctly. Currently I do it like this (entire code can be found below):
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
})
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Get new tab!</h3>
</div>
<button type="button" id="process_input">no alert</button>
<a href="/html_in_tab" class="button" target='_blank'>alert</a>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#process_input').bind('click', function() {
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
})
return false;
});
});
</script>
</body>
</html>
and the flask file:
from flask import Flask, render_template, request, jsonify
import json
# Initialize the Flask application
app = Flask(__name__)
#app.route('/html_in_tab')
def get_html():
# provided by an external tool
# takes the user input as argument (below mimicked by a simple string concatenation)
return '<!DOCTYPE html><title>External html</title><div>Externally created</div><script>alert("WORKING");</script>'
#app.route('/_process_data')
def data_collection_and_processing():
# here we collect some data and then create the html that should be displayed in the new tab
some_data = json.loads(request.args.get('some_data'))
# just to see whether data is retrieved
print(some_data)
# oversimplified version of what actually happens; get_html comes from an external tool
my_new_html = get_html() + '<br>' + some_data
print(my_new_html)
# this html should now be displyed in a new tab
return my_new_html
#app.route('/')
def index():
return render_template('index_new_tab.html')
if __name__ == '__main__':
app.run(debug=True)
I think you need something like this:
var win = window.open("", "_blank",);
win.document.write('<!DOCTYPE html><title>External html</title><div>Externally created</div><script>(function(){alert(1);})();</script>');
when you open the popup, this executes JavaScript. You could add data and do whatever you want inside <script>(function(){alert(data);})();</script>
After the HTML has been added to the page, you could execute a function to run it. This would require wrapping your scripts with functions like this:
function onStart() {
// Your code here
}
Then after the HTML is added to the page, run the function:
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
onStart();
})
Instead of...
var win = window.open("", "_blank");
win.document.body.innerHTML = data;
Use jquery to load the html and wait for loading to complete:
$.get('/_process_data', {
some_data: JSON.stringify('some data'),
}).success(function(data) {
var w = window.open("", "_blank");
$(w.document.body).load(data, function () {
//execute javascript here
});
})
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'm building a phone app with Phonegap well, actually with Steroids.js which is built on top of Phonegap. Right now, all I want to do is retrieve the list of contact names and numbers from my phone upon the launching of my app. I took a look at the Contacts api here and I thought I was using it correctly. Below is the script I have inside of my head tags. What have I done wrong?
<script src="http://localhost/cordova.js"></script>
<script src="components/steroids-js/steroids.js"></script>
<script src="javascripts/application.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
function onSuccess(contacts) {
alert('ons');
for (var i = 0; i < contacts.length; i++) {
//trying to display contacts in an alert message when I launch my app
alert("Display Name = " + contacts[i].displayName);
}
}
// onError: Failed to get the contacts
function onError(contactError) {
alert('onError!');
}
</script>
In your above code your cordova.js file is misplaced somewhere.
like
<script src="http://localhost/cordova.js"></script>
You need to copy that cordova.js file into assest/www/ folder (like assest/www/cordova.js)
so it becomes like below in your html file
<script src="cordova.js"></script>