Uncaught ReferenceError: gapi is not defined at makeApiCall? - javascript

function makeApiCall(){
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.insert
console.log(request);
({
'calendarId': '',
"resource": resource
});
});
}

Unless you have forgotten to post a section of your code you have probably forgotten to register the library, as well as authorizing the user.
<script src="https://apis.google.com/js/client:platform.js"></script>
full example using Google sign-in
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello cal v3 </title>
<!-- Create a client id on Google developer console. Web credentials https://youtu.be/pBVAyU4pZOU -->
<meta name="google-signin-client_id"
content="YourClientId">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/calendar">
</head>
<body>
<h1>Hello cal v3 </h1>
<!-- The Sign-in button. This will run `getFileAsync()` on success. -->
<p class="g-signin2" data-onsuccess="makeacall"></p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Query the API and print the results to the page.
async function makeacall() {
try {
await gapi.client.load('calendar', 'v3');
const response = gapi.client.calendar.events.insert({
calendarId: 'XXX',
resource: resource
});
displayResults(response)
} catch (e) {
console.error('Error getting files', e)
}
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
Redirect uri mismatch JavaScript origin error
Make sure that you have configured your web client properly on Google developer console and added the proper javascript origin. Simple solution for redirect_uri_mismatch error with JavaScript

you need to init gapi on page load
gapi.auth2.init({
client_id: 'xxxxxxxxxxx'
});

Related

How to build and display Consent Pane PLAID with PHP

i want to integrate PLAID system on my project based Laravel framework. Currently i'm developing on step to display Consent Pane PLAID from this doc PLAID LINK DOC. I'm using the javascript code. but i still failed to integrate it. here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Plaid</title>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
</head>
<body >
plaid
</body>
<script>
const handler = Plaid.create({
token: 'link-sandbox-xxx',
onSuccess: (public_token, metadata) => {
console.debug("onSuccess");
console.log('public_token: ' + public_token);
console.log('account ID: ' + metadata.account_id);
},
onLoad: () => {
console.debug("onLoad");
},
onExit: (err, metadata) => {
console.debug("onExit");
console.log('metadata ' + metadata);
},
onEvent: (eventName, metadata) => {
console.debug("onEvent");
},
receivedRedirectUri: "https://domainname.com/plaid",
});
handler.open();
</script>
</html>
Display error
POST https://sandbox.plaid.com/link/workflow/start 400 (Bad Request)
Error: oauth uri does not contain a valid oauth_state_id query parameter.
i already added new URL my API menu on PLAID Dashboard but still display this error.
Please help. How do i able to integrate that on my laravel?
The receivedRedirectUri should not be set when initializing Link for the first time. It is used when initializing Link for the second time, after returning from the OAuth redirect.

Issue interfacing smart contract with the front end

I'm actually trying to write a simple smart contract with front end that takes a value from the user and saves that in the variable in the smart contract.
The index.html part of my project is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="message"></div>
<form method="POST">
<div><input id= "message" name = "message" type= "text">
</div>
<div>
<button type="button" id="register">Register</button>
</div>
</div>
</form>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
And app.js is
App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function() {
return App.initWeb3();
},
initWeb3: function() {
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("HelloWorld.json", function(hello) {
// Instantiate a new truffle contract from the artifact
App.contracts.HelloWorld = TruffleContract(hello);
// Connect provider to interact with contract
App.contracts.HelloWorld.setProvider(App.web3Provider);
return App.bindEvents();
});
},
bindEvents: function() {
$(document).on('click', '#register', function(){ var msg = $('#message').val(); App.handleMessage(msg); });
},
handleMessage: function(msg){
var hwinstance;
App.contracts.HelloWorld.deployed().then(function(instance) {
hwinstance = instance;
return hwinstance.setMessage(msg);
}).then( function(result){
if(result.receipt.status == '0x01')
alert("successfully")
else
alert("failed due to revert")
}).catch( function(err){
alert("failed")
})
}
};
$(function() {
$(window).load(function() {
App.init();
console.log('starting app.js');
});
});
The smart contract code that I've written is
pragma solidity 0.5.16;
contract HelloWorld {
string private message = "hello world";
function getMessage() public view returns(string memory) {
return message;
}
function setMessage(string memory newMessage) public {
message = newMessage;
}
}
When I ran the commands truffle complie and truffle migrate, it showed no errors but when I ran 'npm run dev' the page says "Cannot GET /".
I'm not able to understand where the mistake is. Please help!
Is there any other way of interfacing the frontend to the smart contract?
Your local server cannot find your page either because it is in the wrong directory or the local server has not been installed. Run npm install --save-dev lite-server. In the package.json you should have something like
"script": {
"dev": "lite-server",
...
}
Move your index.html and App.js into src/ directory you create at the root of the project. Run npm run dev to check again. It should work. If you are interested in an easy to use truffle box with react, I have developed a truffle box with React + Material-UI. Take a look here https://github.com/rouftom/truffle-react-material

Keycloak login returns 404 using JavaScript adapter

I'm using Keycloak's bower package to create a very basic demo HTML/JS app. I have Keycloak running locally and keycloak.init() seems to work (no error triggered). However when I call keycloak.login() a 404 is returned. Might the login URL be wrongly created by the adapter?
The URL returned by keycloak.createLoginUrl() is
https://<keycloak url>/realms/<realm>/protocol/openid-connect/auth?client_id=account&redirect_uri=file%3A%2F%2F%2FUsers%2Fjgallaso%2FProjects%2Fdemos%2Fkeycloak-simple-web-client%2Findex.html&state=b167dc0b-3e5b-4c67-87f7-fd5289fb7b8f&nonce=1e2cb386-51db-496a-8943-efcf4ef5d5e1&response_mode=fragment&response_type=code&scope=openid
And this is my entire code:
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init()
.success(authenticated => {
document.getElementById("login")
.addEventListener("click", () => { keycloak.login(); });
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
Response is a plain:
ERROR 404: Not Found
You have 2 posibilities :
invoque login automatically in init method
login manually after call init without params
1)
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init('login-required')
.success(function(authenticated) => {
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
2)
keycloak.init().success(function(authenticated) {
if(authenticated == true){
alert('usuario logeado');
}else{
alert('usuario no logeado');
keycloak.login();
}
}).error(function() {
alert('failed to initialize');
});
I had trouble trying directly from the management.
file://c:/example.html
To do a better test you should leave your index.html on a local test server.
What I did was install the web server plugin for chrome and it worked for me.
I hope it'll help you.
regards

Workbox, staleWhileRevalidate called only once on image

I'm developing a PWA and I'm trying to use workbox to manage the service-worker and the caching of assets.
In my PWA I have to show all the newer images if the device is online and, if not, the images in the cache.
When I try to implement it I see that the staleWhileRevalidate method on image is called only once in the page for each image, also if I try to refresh multiple times. I need to close the webpage and when I reopen it the image is updated correctly. It's normal that it work in this way?
When I try it with localhost, the staleWhileRevalidate is called every time I reload the page, but when I load the website on a remote server, the app does not work anymore in this way.
service-worker.js:
importScripts('workbox-sw.prod.v2.0.0.js');
const workboxSW = new WorkboxSW();
var CACHE_NAME = 'my-cache';
var filesToCache = [
'imgs/images.png',
'index.html'
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
console.log('[ServiceWorker] Caching App Shell');
return cache.addAll(filesToCache);
})
);
});
workboxSW.router.registerRoute(
/.*\/imgs\/(.*\/)?.*\.(png|jpg|jpeg|gif)/,
({event}) => {
console.log("staleWhileRevalidate called);
return workboxSW.strategies.staleWhileRevalidate({cacheName: CACHE_NAME}).handle({event}).catch((error) => {
console.log("Error staleWhileRevalidate");
return error;
});
}
);
index.html:
<!DOCTYPE html>
<html>
<head >
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title class="title">PWA</title>
</head>
<body>
<div class="container">
<img src="imgs/image.png">
</div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
console.log('ServiceWorker registration successful);
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script>
</body>
</html>
Installing (not in localhost)
First Reload (not in localhost)
Second Reload (and more times)

Getting email from LinkedIn Javascript API reliably

Keen to get at the user's email reliably, there doesn't appear to be anything in the API documentation about this from LinkedIn. I have the cod working which grabs the basic profile and I've tried what I can find on the web to get additional fields. But this doesn't return anything. Here is the code:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 11111111111
onLoad: onLinkedInLoad
authorize: true
scope: r_basicprofile
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
var fields = ['firstName', 'lastName', 'emailAddress'];
IN.API.Profile("me").fields(fields).result(onSuccess).error(onError);
}
</script>
and HTML:
<script type="in/Login"></script>
I do not know if it is possible with the current version to return the email or the email is user setting so varies with each user.
You are missing r_emailaddress to the scope:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 11111111111
onLoad: onLinkedInLoad
authorize: true
scope: r_basicprofile r_emailaddress
</script>
Also be sure you are using the right syntax for the fields:
var fields = ['first-name', 'last-name', 'email-address'];
And finally check in your app setting on LinkedIn developer that you grant r_emailaddress access.

Categories

Resources