How to get new messages using gmail api - javascript

I'm writing a Google Chrome browser extension. It uses gmail-api and I want to receive incoming messages coming to the email address of the user who is logged in. How do I implement this in the background script in terms of code. I know that gmail api uses post requests such as watсh, then I don’t know how to implement the code so that I can see messages that would come in real time and my background script would be updated during this event.
My application uses the methods of pull alerts, and accordingly the documentation says that I should use requests such as
https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/pull
https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/acknowledge
How can I use all this in my code so that my script is constantly updated when I receive a new message and is it even possible in javascript?
function POST_request(method,url,_async,params)
{
let xhr= new XMLHttpRequest();
xhr.open(method,url,_async);
xhr.setRequestHeader('Authorization', 'Bearer ' + current_token);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(params));
return(xhr.responseText);
}
let tmp={
"topicName":"projects/myprofect/topics/mytopic",
"labelFilterAction":"include",
"labelIds": ["INBOX"]
};
console.log(POST_request("POST","https://www.googleapis.com/gmail/v1/users/me/watch",false,tmp));
This query works by returning the view body
{
"historyId": "678576",
"expiration": "1555318376357"
}

Related

Javascript Fetch - How to Fix Failed to Fetch Error (probably from making HTTP request on HTTPS site?)

This is the React app (and code). It generates 3 random objects (from list of 500+ objects stored locally). I want to call IconFinder API when the random objects are chosen and just display the icons then (instead of finding 500 icons beforehand).
I'm running it on Windows 10 with Google Chrome Version 84.0.4147.89 (Official Build) (64-bit). The code is hosted on Codesandbox. You can take a look at all the code here or just the output and Chrome dev tools here
Demo XHR GET request that they show in their Docs
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.iconfinder.com/v4/icons/search?query=arrow&count=10");
xhr.setRequestHeader("authorization", "Bearer <API KEY HERE>");
xhr.send(data);
My Fetch GET request
let url = "https://api.iconfinder.com/v4/icons/search?query=arrow&count=1&premium=0";
let h = new Headers();
h.append("Accept", "application/json");
h.append(
"authorization",
"Bearer <API KEY HERE>"
);
let req = new Request(url, {
method: "GET",
headers: h,
credentials: "include"
});
fetch(req)
.then(response => {
if (response.ok) {
return response;
} else {
throw Error(`Request rejected with status ${response.status}`);
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error("Error: ", err.message));
Output: Console reads Error: Failed to fetch
In the Chrome Dev Tools, Network Tab (Screenshot 1) I see a file of type fetch (Screenshot 2) and file of type json (Screenshot 3 and 4) have something wrong with them.
What I've tried
Fetch GET requests work for Codesandbox with the Star Wars API (no authentication required), but not for MovieDB API (authentication in url not headers - ex. https://api.themoviedb.org/3/search/movi?api_key=<INSERT KEY>?<other parameters here> ). It threw an error because response.ok wasn't true.
I tried fetching data from the IconFinder API and the MovieDB API on other online IDEs (like Scrimba.com and repl.it). Those also didn't work.
I've tried using XHR requests and fetch await requests instead of fetch requests chained with then promises on different platforms. No luck.
I've double-checked how to set the authentication headers with the IconFinder API documentation.
I've also double-checked that my API key is registered to the url I'm calling it from and not restricted to any domains (Screenshot 5)
Looked through these Forums: it looks like I have something going wrong with making fetch requests from a HTTPS page, but I'm not sure what I need to change in my code based on that information. I've tried reloading the page on Codesandbox as http, but it redirects me to https automatically (Source 1, Source 2, Source 3, Source 4)
This is my first time making API calls so I don't really know what the possibilities are for what could go wrong and how to fix it. I've tried looking at some other StackOverflow threads but I'm having a hard time understanding them. Next, I'm going to try transferring the React App to a local file and seeing if I can make fetch requests there. Anyone have any thoughts on what else I should try?
The issue was based on a CORS error. A friend of mine told me to test the api call to:
https://api.iconfinder.com/v4/icons/search?query=arrow&count=1&premium=0
via https://reqbin.com/. It worked on the testing website.
Then, he told me to just make the request to that url with this Cors Anywhere tool. Like this:
https://cors-anywhere.herokuapp.com/https://api.iconfinder.com/v4/icons/search?query=arrow&count=1&premium=0
That worked on my local development environment. Still not sure exactly HOW it works.

Sending email from browser mailgun

I want to send a simple email from the browser using mailgun. I send a working email from postman and with the download code function I managed to get the javascript code which is:
var data = new FormData();
data.append("from", "Mailgun Sandbox <postmaster#sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org>");
data.append("to", "Example <example#gmail.com>");
data.append("subject", "Hello from Mailgun");
data.append("text", "Congratulations Example, you just sent an email with Mailgun! You are truly awesome!");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api:key-75a05cfds8c66bd1y4c3e854305438e5#api.mailgun.net/v3/sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org/messages");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "0a3ad9d5-22b5-6308-d6e7-59f66360fa26");
xhr.send(data);
But when I execute this code from my browser (firefox) it does nothing. What am I doing wrong?
Changing the url from
https://api:key-75a05cfds8c66bd1y4c3e854305438e5#api.mailgun.net/v3/sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org/messages
to
https://api.mailgun.net/v3/sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org/messages
seems to execute, is the api:key-xx part invalid?
Don't do this. This is not an appropriate use of the Mailgun API.
By delivering this Javascript to a browser, you are giving them access to your Mailgun API key. This API key is not limited in any way whatsoever -- a malicious client could misuse the key to send an unlimited number of messages to any recipient they want, potentially racking up large bills and/or getting your account blocked for spam.
Use the Mailgun API on the server side. If you need to send messages via Javascript, create an endpoint in your application which calls the Mailgun API with appropriate restrictions in place.

Page Redirect and set request custom request header

I am looking for a way to redirect to another web app and set a custom request header. This is manly because the web app that I am going to is expecting a custom header for the user name call "REMOTE_USER" where I will set the user name to.
I was exploring the use of a java servlet or maybe writing some java script to do this.
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("REMOTE_USER", "User1");
window.location.href = "http://myserver.com:8080/webapp/";
I am seeing that the page is getting redirected but don't see any custom request headers
function customHeader(remoteinput, userinput) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader(remoteinput, userinput);
window.location.href = "http://myserver.com:8080/webapp/";
}
Now execute your function:
customHeader("something", "user42");
If I am misinterpreting your question, please reply!

USPS Tracking API Issue with XMLHttpRequest

I'm new to web development. I was trying to make a call to USPS Tracking API using XMLHttpRequest. Eventhough, I'm able to get the response when I paste below URL into address bar, I'm not able to get any response with code.
http://production.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=<TrackRequest USERID="xxxxxx"><TrackID ID="EJ958083578US"></TrackID></TrackRequest>
This is the code I was trying:
xhr.onreadystatechange = handleStateChange;
xhr.open("GET","http://production.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=<TrackRequest USERID='xxxxxx'><TrackID ID='EJ958083578US'></TrackID></TrackRequest>" , isAsync);
xhr.send();
It will not work with "GET", use "POST". It will work.

I dont understand how to implement the Deleting Requests in request dialog

I have read the document here
but I don't understand how should I implement it right.
In my facebook app I use apprequests from JS api like this:
function newInvite() {
var msg = document.getElementById('msg_look_id').value;
var receiverUserIds = FB.ui({
method: 'apprequests',
message: msg,
title: "Select friends to send your gift",
},
function (response) {
alert("IDS : " + response.request_ids);
});
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
then the user see the request in its app request icon (with the red numbers )
the user click it , but then how do I implement the delete request ?
When the user arrives at your app’s canvas page following a request, there is a parameter called request_ids passed to your app.
Since Facebook calls apps in the iframe using the HTTP method POST, I guess this is also a POST parameter (although it is not explicitly mentioned in the docs). That means you have no access to it using pure client-side JavaScript; you have to use a server-side script to get the content of this parameter.

Categories

Resources