I have created google oath code and it is working on localhost but when i move this code on server this is not working i have added both the url localhost and my server url, I have changes the keys can anyone tell me why this is not console.log(response) after login on server
even it is not working on Localhost:8000 but when i run this locathos/abc.html it give me response
Please help me
here is my code
<script type="text/javascript"
src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"> </script>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<div id="abc1"> </div>
<div id="abc2"> </div>
<div id="abc3"> </div>
<div id="abc4"> </div>
<script type="text/javascript">
const CLIENT_ID = '8v1c.apps.googleusercontent.com';
const API_KEY = '9nuRfJt_skX0Hyc';
const DISCOVERY_DOC = 'https://script.googleapis.com/$discovery/rest?version=v1';
const SCOPES = 'https://www.googleapis.com/auth/script.projects';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
function gapiLoaded() {
gapi.load('client', initializeGapiClient);
}
async function initializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await createScript();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
async function createScript() {
let response;
jQuery("#abc1").html(response);
try {
const createRequest = {
resource: {
title: 'My Script',
},
};
response = await gapi.client.script.projects.create(createRequest);
const updateContentRequest = {
scriptId: response.result.scriptId,
resource: {
files: [{
name: 'hello',
type: 'SERVER_JS',
source: 'function helloWorld() {\n console.log("Hello, world!");\n}',
}, {
name: 'appsscript',
type: 'JSON',
source: '{"timeZone":"America/New_York","' +
'exceptionLogging":"CLOUD"}',
}],
},
};
response = await gapi.client.script.projects.updateContent(updateContentRequest);
console.log('++++++++++++++++++++++++++++++++++++')
console.log(response)
jQuery("#abc2").html(JSON.stringify(response['result']['files'][0]['lastModifyUser']));
const output = `Script URL: https://script.google.com/d/${response.result.scriptId}/edit`;
console.log('-------------------------------')
console.log(output)
jQuery("#abc3").html(output);
document.getElementById('content').innerText = output;
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
Related
I am trying to retrieve the list of classrooms I handle, and I tried implementing this code that I retrieved from Google Classroom Javascript Quickstart and implemented it on my Vue3 project.
Here's my code:
<script>
import axios from 'axios';
const CLIENT_ID = '<MY_CLIENT_ID>;
const API_KEY = '<MY_API_KEY>';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://classroom.googleapis.com/$discovery/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/classroom.courses.readonly';
let tokenClient;
let gapiInited = false;
let gisInited = false;
let gapi = window.gapi;
export default{
data(){
return {
error: "",
courses: "",
};
},
methods: {
gapiLoaded(){
axios.get("https://apis.google.com/js/api.js").then(()=>{
gapi.load('client', intializeGapiClient);
})
},
async initiazlieGapiClient(){
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
},
gisLoaded(){
axios.get("https://accounts.google.com/gsi/client").then(() => {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '',
});
gisInited = true;
maybeEnabledButtons();
})
},
maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
},
handleAuthClick(){
tokenClient.callback = async (resp) => {
if(resp.error !== undefined) {
throw(resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
};
if(gapi.client.getToken() === null) {
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
tokenClient.requestAccessToken({prompt: ''});
}
},
handleSignoutClick(){
const token = gapi.client.getToken();
if(token !== null){
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
},
async listCourses() {
let response;
try {
response = await gapi.client.classroom.courses.list({
pageSize: 10,
});
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const courses = response.result.courses;
if (!courses || courses.length == 0) {
document.getElementById('content').innerText = 'No courses found.';
return;
}
// Flatten to string to display
const output = courses.reduce(
(str, course) => `${str}${course.name}\n`,
'Courses:\n');
document.getElementById('content').innerText = output;
},
mounted: function(){
this.gapiLoaded();
this.gisLoaded();
},
},
}
</script>
I'm having 5 errors, saying that it
Compiled with problems: ERROR [eslint]
'initializedGapiClient' is not defined no-undef
'maybeEnableButtons' is not defined no-undef
'google' is not defined no-undef
'maybeEnableButtons' is not defined no-undef
'google' is not defined no-undef
5 problems (5 errors, 0 warnings)
What could be the solution to my problem here? Did I implemented it wrong? Thank you for anyone that will help me!
I got this code off github which allows you to connect to MetaMask using web3.js and also to make payment. I then modified it to
Display a Connect Button when user is not logged in by checking if the content of an element is empty and if it is not empty, the connect button is hidden.
Retrieve the connected wallet address which is in the element that hides the button.
I want the connected wallet to show up and hide the Connect button as soon as MetaMask is connected but it does not do that until i manually reload the page
Below is my code
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://unpkg.com/#metamask/legacy-web3#latest/dist/metamask.web3.min.js"></script>
</head>
<body>
<div>
<div id="selected-account"></div>
<button class="pay-button">Pay</button>
<div id="status"></div>
<div id="accTabs"></div>
</div>
<script type="text/javascript">
async function initWeb3() {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
await ethereum.enable();
window.location.reload();
} catch (err) {
$("#status").html("User denied account access", err);
}
} else if (window.web3) {
return (window.web3 = new Web3(web3.currentProvider));
} else {
return $("#status").html("No Metamask (or other Web3 Provider) installed");
}
}
selectedAccount = ethereum.selectedAddress;
document.querySelector("#selected-account").textContent = selectedAccount;
$(".pay-button").click(async () => {
await initWeb3();
// paymentAddress is where funds will be send to
const paymentAddress = "0x192c96bfee59158441f26101b2db1af3b07feb40";
const amountEth = "1";
web3.eth.sendTransaction(
{
to: paymentAddress,
value: web3.toWei(amountEth, 'ether')
},
(err, transactionId) => {
if (err) {
console.log("Payment failed", err);
$("#status").html("Payment failed");
} else {
console.log("Payment successful", transactionId);
$("#status").html("Payment successful");
}
}
);
});
</script>
<script>
if ($('#selected-account').text() == '') {
document.getElementById("accTabs").innerHTML = '<button onclick="initWeb3()">Connect Ethereum</button>';
} else {
}
</script>
</body>
</html>
Your help will be appreciated!
Thanks for your assistance.
you should use onload function like this window.onload = async function () { when it works you need to verify if window have ethereum if everything is ok then connect to a provider using new Web3.providers.HttpProvider
window.onload = async function () {
const detectMM = () => typeof window.ethereum !== "undefined";
if (detectMM) {
document.getElementById("enableMM").getAttribute("disabled", false);
try {
const provider = new Web3.providers.HttpProvider(
"HTTP://127.0.0.1:7545"
);
web3 = new Web3(window.ethereum);
web3Host = new Web3(provider);
await connect();
await web3.eth.net
.isListening()
.then(
() =>
(document.getElementById(
"network"
).innerHTML = `available network`)
)
.catch(
(e) =>
(document.getElementById(
"network"
).innerHTML = `Something went wrong: ${e}`)
);
} catch (error) {
alert(error);
}
} else {
document.getElementById("enableMM").getAttribute("disabled", true);
}
I am using peerJS for screen sharing feature and flutter for web app, I'm able to call javascript functions in flutter but not able to pass values from Javascript and Flutter and make them listen in flutter.
this is my script.js:
const PRE = "Devcom"
const SUF = "Community"
var room_id;
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var local_stream;
var screenStream;
var peer = null;
var currentPeer = null
var screenSharing = false
function createRoom() {
console.log("Creating Room")
let room = document.getElementById("room-input").value;
if (room == " " || room == "") {
alert("Please enter room number")
return;
}
room_id = PRE + room + SUF;
peer = new Peer(room_id)
peer.on('open', (id) => {
console.log("Peer Connected with ID: ", id)
hideModal()
getUserMedia({ video: true, audio: true }, (stream) => {
local_stream = stream;
setLocalStream(local_stream)
}, (err) => {
console.log(err)
})
notify("Waiting for peer to join.")
})
peer.on('call', (call) => {
call.answer(local_stream);
call.on('stream', (stream) => {
setRemoteStream(stream)
})
currentPeer = call;
})
}
function setLocalStream(stream) {
let video = document.getElementById("local-video");
video.srcObject = stream;
video.muted = true;
video.play();
}
function setRemoteStream(stream) {
let video = document.getElementById("remote-video");
video.srcObject = stream;
video.play();
}
function hideModal() {
document.getElementById("entry-modal").hidden = true
}
function notify(msg) {
let notification = document.getElementById("notification")
notification.innerHTML = msg
notification.hidden = false
setTimeout(() => {
notification.hidden = true;
}, 3000)
}
function joinRoom() {
console.log("Joining Room")
let room = document.getElementById("room-input").value;
if (room == " " || room == "") {
alert("Please enter room number")
return;
}
room_id = PRE + room + SUF;
hideModal()
peer = new Peer()
peer.on('open', (id) => {
console.log("Connected with Id: " + id)
getUserMedia({ video: true, audio: true }, (stream) => {
local_stream = stream;
setLocalStream(local_stream)
notify("Joining peer")
let call = peer.call(room_id, stream)
call.on('stream', (stream) => {
setRemoteStream(stream);
})
currentPeer = call;
}, (err) => {
console.log(err)
})
})
}
function startScreenShare() {
if (screenSharing) {
stopScreenSharing()
}
navigator.mediaDevices.getDisplayMedia({ video: true }).then((stream) => {
screenStream = stream;
let videoTrack = screenStream.getVideoTracks()[0];
videoTrack.onended = () => {
stopScreenSharing()
}
if (peer) {
let sender = currentPeer.peerConnection.getSenders().find(function (s) {
return s.track.kind == videoTrack.kind;
})
sender.replaceTrack(videoTrack)
screenSharing = true
}
console.log(screenStream)
})
}
function stopScreenSharing() {
if (!screenSharing) return;
let videoTrack = local_stream.getVideoTracks()[0];
if (peer) {
let sender = currentPeer.peerConnection.getSenders().find(function (s) {
return s.track.kind == videoTrack.kind;
})
sender.replaceTrack(videoTrack)
}
screenStream.getTracks().forEach(function (track) {
track.stop();
});
screenSharing = false
}
function alertMessage(text) {
alert(text)
}
window.logger = (flutter_value) => {
console.log({ js_context: this, flutter_value });
}
window.state = {
hello: 'world'
}
I am able to call these javascript functions in my flutter app using:
import 'dart:js' as js;
js.context.callMethod('alertMessage', ['Flutter is calling upon JavaScript!']);
I have webRTC.html file below which works fine with my js file attached above:
<html>
<head>
<title>DEVCOM - Rooms</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1 class="title">Devcom</h1>
<p id="notification" hidden></p>
<div class="entry-modal" id="entry-modal">
<p>Create or Join Meeting</p>
<input id="room-input" class="room-input" placeholder="Enter Room ID">
<div>
<button onclick="createRoom()">Create Room</button>
<button onclick="joinRoom()">Join Room</button>
</div>
</div>
<div class="meet-area">
<!-- Remote Video Element-->
<video id="remote-video"></video>
<!-- Local Video Element-->
<video id="local-video"></video>
<div class="meet-controls-bar">
<button onclick="startScreenShare()">Screen Share</button>
</div>
</div>
</body>
<script src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
<script src="script.js"></script>
</html>
but the problem which I am facing is how can I make a flutter widget listen to javascript like instead of using document.getElementById("room-input").value I want to make javascript listen to flutter widgets and variables rather than html id, values...
or Is there any other way which can make html rendering in flutter web I tried webview_flutter, easy_web_view, flutter_html but nothing worked for me as I want to use it in windows chrome (web) few of earlier mentioned plugins are rather legacy and other are only for android and ios
I need to show a simple local notification, just to understand how does it work. Fro this purpose I wrote this code:
askPermissions = async () => {
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
return finalStatus === 'granted';
};
sendNotificationImmediately = async () => {
const notificationId = await Notifications.presentLocalNotificationAsync({
title: 'This is header',
body: 'This is body',
});
console.log(notificationId);
};
And called this method in a such way:
componentDidMount() {
if (this.askPermissions()) {
console.log('Permission presents');
this.sendNotificationImmediately();
} else {
console.log('Denied');
}
}
To wrote this code I used this tutorial. But when I run the app notification isn't shown, but permission presents. So, what's the reason of the problem and how can I solve it?
You can try this,
askPermissions = async () => {
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
} else if (finalStatus === 'granted') {
Notifications.presentLocalNotificationAsync({
title: 'This is header',
body: 'This is body',
});
}
componentDidMount() {
this.askPermissions();
}
Hope this helps.
I used listMessages to get the Id and getMessages to print the snippet, however it doesn't seem to work:
function listMessages() {
gapi.client.gmail.users.messages.list({
'maxResults': 1000,
'userId': 'me',
'format': 'full',
}).then(function(response) {
appendPre('Files:');
var messages = response.result.messages;
if (messages && messages.length > 0) {
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
var message_Id = message.id;
window.message_Id = message_Id;
getMessages();
}
} else {
appendPre('No files found.');
}
});
}
function getMessages() {
gapi.client.gmail.users.messages.get({
'maxResults': 1000,
'id': message_Id,
'userId': 'me',
'format': 'full',
}).then(function(response) {
var messages = response.result.messages;
if (messages && messages.length > 0) {
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
appendPre(message.threadId + ' (' + message.snippet + ')');
}
else {
appendPre('No files found.');
}
});
}
For some reason it only returns with no files found, how can I get it to print out the snippet and Id?
First, I did this steps https://developers.google.com/gmail/api/quickstart/nodejs
After That, I did like this:
const fs = require('fs');
const { google } = require('googleapis');
const TOKEN_PATH = 'token.json';
class ReadEmail {
constructor(_dominio) {
this.credentials = null;
this.auth = null;
this.message = null;
this.dominio = _dominio;
}
async setup() {
this.credentials = await this.getCredentials();
this.auth = await this.getAuthorize();
this.message = await this.getLastMessage();
}
getCredentials() {
return new Promise((resolve, reject) => {
fs.readFile('credentials.json', (err, content) => {
if (err) reject('Error loading client secret file:' + err);
resolve(JSON.parse(content));
});
});
}
getAuthorize() {
return new Promise((resolve, reject) => {
const { client_secret, client_id, redirect_uris } = this.credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) reject('Erro ao pegar o Token: ' + err);
oAuth2Client.setCredentials(JSON.parse(token));
resolve(oAuth2Client);
});
});
}
getLastMessage() {
return new Promise((resolve, reject) => {
const gmail = google.gmail({ version: 'v1', auth: this.auth });
var request = gmail.users.messages.list({
userId: 'me',
labelIds: 'INBOX',
maxResults: 10,
});
request.then(ret => {
let id = ret.data.messages[0].id;
var request2 = gmail.users.messages.get({
userId: 'me',
id: id,
});
request2.then(ret2 => {
let msg = ret2.data.payload.body.data;
let buff = new Buffer.from(msg, 'base64');
let text = buff.toString('ascii');
console.log(text)
resolve(text);
});
});
});
}
}
new ReadEmail('_dominio').setup();
To understand better, try following the quickstart for JavaScript, this shows a simple JavaScript application that makes requests to the Gmail API.
<!DOCTYPE html>
<html>
<head>
<title>Gmail API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<p>Gmail API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '<YOUR_CLIENT_ID>';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listLabels();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print all Labels in the authorized user's inbox. If no labels
* are found an appropriate message is printed.
*/
function listLabels() {
gapi.client.gmail.users.labels.list({
'userId': 'me'
}).then(function(response) {
var labels = response.result.labels;
appendPre('Labels:');
if (labels && labels.length > 0) {
for (i = 0; i < labels.length; i++) {
var label = labels[i];
appendPre(label.name)
}
} else {
appendPre('No Labels found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Things to remember:
Turn on the Gmail API
After the initial user authorization, calls to gapi.auth.authorize that use immediate:true mode will obtain an auth token without user interaction.
Also follow the links for further reading :
Google Developers Console help documentation
Google APIs Client for JavaScript documentation
Gmail API reference documentation
This will help you understand and familiarize yourself with the different methods and function in Gmail API.