I am creating a webworks application, so my code is not being placed on a server. The youtube data api does not work when accessing from your local file system, but that it how my application works. I need a work around, or a way to make a local private web server with pure js, no command line tools.
html
<!DOCTYPE HTML>
<html>
<head>
<title>add song</title>
<link type="text/css" href="../css/AS_Style.css" rel="stylesheet">
</head>
<body>
<div id="main">
<p id="response">a</p>
<form action="#">
<p><input type="text" id="search" placeholder="Type something..." autocomplete="off" class="form-control" /></p>
<p><input type="submit" value="Search" class="form-control btn btn-primary w100"></p>
</form>
<div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="../js/AS.js"></script>
<script src="https://apis.google.com/js/api.js"></script>
<script>
function init() {
gapi.client.init({
'apiKey':'key here',
});
search();
}
gapi.load('client',init);
</script>
</body>
</html>
JavaScript
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
function search() {
$("form").on("submit", function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
});
});
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
};
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
Can you show the code you're using to call Youtube's API? You can get the API data with pure javascript:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id=CHANNEL_ID&maxResults=1&fields=items&order=date&key=API_KEY", false);
xhr.send();
document.write(xhr.responseText);
Did you try triggering a shell script via javascript, and making the shell script run the API code?
Apparently this worked: https://stackoverflow.com/a/21484756/7922428
Youtube API doesnt work without connection to the internet, which when your locally testing, is done through local servers.
Here are my suggestions:
Use Nodejs
Use python -m SimpleHTTPServer
Related
My Html form has dropdown which load dynamic options using api request. I'm using google HTML Service to link google app script with html file. My problem is my modal dialog getting disappear as soon as it appears.
======== Script ========
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Call API')
.addItem('Display results','html')
.addToUi();
}
function html(){
var html = HtmlService.createTemplateFromFile('load');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Input API Creddentials');
}
function getClients() {
var response = UrlFetchApp.fetch("http://myurl does here");
var fact = JSON.parse(response.getContentText());
var optionsHTML = [];
for (var i = 0; i < fact.length-1;i+=1) {
optionsHTML.push(fact[i].clientId.client);
}
SpreadsheetApp.getUi().alert(optionsHTML);
return optionsHTML;
}
======= HTML File ====
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form >
<div>
<select id="optionList" name="optionList">
<option>Loading...</option>
</select>
</div>
Username:
<input type="text" name="username"> <br />
Password:
<input type="password" name="password"> <br />
<input type="button" value="OK" onclick="google.script.run.callNumbers(this.parentNode);google.script.host.editor.focus();" />
</form>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function () {
google.script.run.withSuccessHandler(buildOptionList)
.getClients();
});
function buildOptionList(clients) {
var list = $('#optionList');
list.empty();
for (var i = 0; i < clients.length; i++) {
list.append(new Option(clients[i]));
}
}
</script>
</html>
The problem occurs due to
// The code in this function runs when the page is loaded.
$(function () {
google.script.run.withSuccessHandler(buildOptionList)
.getClients();
});
because getClients() shows an alert and Google Apps Script doesn't allow to have a Google Sheets UI alert and modal dialog shown simultaneosly.
We are developing a excel plugin using Excel JS. The server code written in java and deployed in wildfy server.
Through excel plugin I'm unable to make the rest call to retrieve the user data. The aim is to perform login operation and retrieve the excel byte format stored at server and display in excel.
Any suggestions? Following is sample code which we tried so-far.
index.html
<body class="ms-font-m ms-welcome">
<div id="content-header">
<div class="padding">
<h1>Welcome</h1>
</div>
</div>
<div id="content-main">
<button id="ping-server3" onclick="pingServer2()">Ping server2</button>
<p id="demo"></p>
<p id="demo1"></p>
<button id="ping-server">Ping server</button>
<p></p>
<div class="padding">
<form>
<div class="container">
<label for="uname"><b>Username</b></label>
<input id="uname" type="text" placeholder="Enter Username"
name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw"
required>
<button id="login-button" onclick="pingServer2()">Login</button>
</div>
<div class="container" style="background-color:#f1f1f1">
<span class="psw">Need password help?</span>
</div>
</form>
</div>
</div>
<script type="text/javascript" src="node_modules/core-js/client/core.js">
</script>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.js">
</script>
<script type="text/javascript" src="node_modules/office-ui-fabric-
js/dist/js/fabric.js"></script>
<script type="text/javascript" src="app.js" ></script>
<script type="text/javascript" src="utility.js" ></script>
</body>
app.js
(function () {
Office.initialize = function (reason) {
$(document).ready(function () {
if (!Office.context.requirements.isSetSupported('ExcelApi', 1.7)) {
alert("ERROR");
console.log('Sorry. The tutorial add-in uses Excel.js APIs that are
not available in your version of Office.');
}
$('#login-button').click(createTable);
});
};
function createTable() {
axios({
method: 'post',
url: 'http://localhost:8183/x/operation.do?&operationId=LOGIN_USER',
data: {emailAddress : 'x#xyz.com,password : '123#asdA'}
})
.then(response => {
$('#demo').innerHTML = response.data;
content=response.data.uiUser.createdBy;
$('#demo1').innerHTML = content;
})
.catch(error => {
$('#demo').innerHTML = response.status;
});
Excel.run(function (context) {
const currentWorksheet =
context.workbook.worksheets.getActiveWorksheet();
const expensesTable = currentWorksheet.tables.add("A1:D1", true
/*hasHeaders*/);
expensesTable.name = "ExpensesTable";
expensesTable.getHeaderRowRange().values = [["Date", "Merchant",
"Category", "Amount"]];
expensesTable.rows.add(null /*add at the end*/, [["1/1/2017", "The
Phone Company", "Communications", "120"], ["1/2/2017", "Northwind
Electric Cars", "Transportation", "142.33"], ["1/5/2017", "Best For You
Organics Company", "Groceries", "27.9"], ["1/10/2017", "Coho Vineyard",
"Restaurant", "33"], ["1/11/2017", "Bellows College", "Education",
"350.1"], ["1/15/2017", "Trey Research", "Other", "135"], ["1/15/2017",
"Best For You Organics Company", "Groceries", "97.88"]]);
expensesTable.columns.getItemAt(3).getRange().numberFormat =
[['€#,##0.00']];
expensesTable.getRange().format.autofitColumns();
expensesTable.getRange().format.autofitRows();
return context.sync();
}).catch(function (error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}
})
the URL you're trying to POST is in http format:
http://localhost:8183/x/operation.do?&operationId=LOGIN_USER
The Excel AddIn is deployed using https.
If you inspect the AddIn, using the F12 Debugger Tools, you will see a Mixed Content error.
Mixed Content: The page at
'https://Your_AddIn_Url' was loaded over HTTPS, but requested an insecure resource
'http://localhost:8183/x/operation.do?&operationId=LOGIN_USER'. This request has
been blocked; the content must be served over HTTPS.
Using an https endpoint should solve your issue.
I've just implemented invisible recaptcha into a web form. Everything works fine with Chrome. But with Microsoft Edge, the image challenge always occurs with every form submission. Which is embarrassing for the users of the website. An idea?
Thanks a lot for your insights and advice :o)
Laurent
Javascript code:
window.onScriptLoad = function () {
var htmlEl = document.querySelector('.g-recaptcha');
var captchaOptions = {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'size': 'invisible',
'badge': 'inline',
callback: window.onUserVerified
};
var inheritFromDataAttr = true;
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
window.onUserVerified = function (token) {
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data : {
'lastname' : $("#lastnameField").val(),
'firstname' : $("#firstnameField").val(),
'city' : $("#cityField").val(),
'postalCode' : $("#postalcodeField").val(),
'g-recaptcha-response' : token
},
success:function(data) {
// informs user that form has been submitted
// and processed
},
error: function(xhr, textStatus, error){
// informs user that there was a problem
// processing form on server side
}
});
};
function onSubmitBtnClick () {
window.grecaptcha.execute;
}
HTML code:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<script type="text/javascript" src="js/petition.js"></script>
...
</head>
<body>
<form id="petitionForm" onsubmit="return false;">
<input id="lastnameField" type="text" name="lastname" placeholder="Lastname" required value="Doe">
<input id="firstnameField" type="text" name="firstname" placeholder="Firstname" required value="John">
<input id="postalcodeField" type="text" name="postalCode" placeholder="Postal Code" required value="ABCDEF">
<input id="cityField" type="text" name="city" placeholder="City" value="Oslo">
....
<input type="submit" name="login" class="g-2" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxx" id="signButton" data-callback='' value="Signer" onclick="onSubmitBtnClick();">
<div class="g-recaptcha" id="recaptchaElement" style="align-content: center"></div>
</form>
...
</body>
</html>
According to this example (https://developers.google.com/recaptcha/docs/display#example) by google
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
I should receive response message and get the alert it but when I try it doesn't display any response and even doesn't call method verifyCallback
I should receive a response after widget rendering, right?
I think you have nothing that causes the grecaptcha.render(... to run.
It needs to be in a handler so that something causes it to run.
verifyCallback should then run as you have correctly specified in the callback parameter
Your callback name should match the callback name passed to the API:
<script type="text/javascript">
var onloadCallback = function(response) {
alert(response);
};
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
I was trying to load Datepicker so that I can later add the value to json request. But it seems that I can't even load the calender in textbox. Idea is to get input date and request it in json.
Well I could mention that without datepicker function it was working fine.
// Portlet JSP in Liferay
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<portlet:resourceURL var="resourceURL">
</portlet:resourceURL>
<portlet:defineObjects />
// jQuery UI sources
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
// Jquery and Ajax Source
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
// JS Function
<script>
$(document).ready(function() {
// Load Date Picker in input box But not working
$( "#datepicker" ).datepicker();
$("#btn").click(function() {
$.ajax({
// Reso
url : '${resourceURL}',
data : {
"PersonID" : $('#PersonID').val(),
"AnotherD" : 2
},//person id to sent, In place of Anotherd I want to add Datevalue
type : 'POST',
dataType : "json",
success : function(data) {
console.log(data);
//Getting Data in return
var x = data.PersonList[1].PersonWeight;
$("#Results").text(x);
$("#Res").text(data.PersonList[1].PersonTemp);
}
});
});
});
</script>
<body>
// Out Put Data
PersonID:
<input type="text" name="PersonID" id="PersonID">
<br>
// Date Picker Textbox
<br>
<p>
Date: <input type="text" id="datepicker" />
</p>
// Refresh Button
<button id="btn">Refresh</button>
<br>Height :
<p id="Results"></p>
<br> Weight:
<p id="Res"></p>
</body>
But its not working, any suggestions?
Remove this line. I think jQuery conflicts is occurring in your case
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
HTH