can i send xhttp request using blogger tags like this - xmlhttprequest

I have this
const xhttp = new XMLHttpRequest();
xhttp.open("GET",`https://www.googleapis.com/blogger/v3/blogs/ID/posts/bypath?path=/2022/02/never-give-up.html&key=KEY`, true);
xhttp.send();
xhttp.onload = function() {
let responseJSON = JSON.parse(this.responseText);
responseJSON.labels[0]==="html"
&&(MY-code);
}
its working fine but i want to do same thing with blogger tags like
<b:eval expr='data:xhttp = new XMLHttpRequest()'/>
<b:eval expr='data:xhttp.onload = function(){data:responseJSON = JSON.parse(this.responseText);}'/>
<b:eval expr='data:xhttp.open("GET","https://www.googleapis.com/blogger/v3/blogs/id/posts/bypath?path=/2022/02/never-give-up.html&key=KEY",true);}'/>
<b:eval expr='data:xhttp.send();}'/>
<b:if cond='data:responseJSON.labels[0]==="html"'>
//my-code
</b:if>
can i do this if posible
its not showing error but also not working

Related

Translate an entire page with Google Translate API

I'm using the google Translate API to translate content that's inside an IFRAME. When using the API, I notice that it returns a array(string) with the translated texts, but when inserting it in the DOM, the entire structure disappears, leaving only the text.
The original Page
The result page after the response of the Google API (translate in Portuguese)
This is the code that I'm using:
function translate(lang) {
var iframe = document.getElementById('mainIframe');
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
var iframeBody = iframeDoc.body;
var iframeHTML = iframeDoc.documentElement;
var iframeText = iframeBody.innerText || iframeHTML.innerText;
var url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=pt&dt=t&q=' + encodeURI(iframeText);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var response = JSON.parse(xhr.responseText);
var translatedText = ''
for (var i = 0; i < response[0].length; i++) {
translatedText += response[0][i][0];
}
iframeDoc.body.innerHTML = translatedText;
}
};
xhr.send();
}
How can I not affect the structure within the Iframe (Not to be like the second image I sent above)? Just replace the original text with what comes in the response and leave the original look.
I've already tried using functions to find the original text in the DOM to replace it with the translated text but without success. In this case, the idea was just to replace the text correspondence literally.
Thanks for your help and thanks in advance

API integration using google app script calling methods on google sheets

I would like to add different API request on a spreadsheet where i already add some google app script code from here in oder to retrieve all orders from a woocommerce external source, however now i want to add another API calling request which allows me to list all products on my woocommerce source. So i type a new function below, modify the endpoint to /wp-json/wc/v3/products according to woocommerce API rest documentation here Woocommerce API rest doc. Here is the code i add to the Github code :
// Custom code to v2 Woocommerce API
function start_syncv2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Products);
fetch_products(sheet)
}
function fetch_products(sheet) {
var ck = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B4").getValue();
var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B5").getValue();
var website = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B3").getValue();
var surl = website + "/wp-json/wc/v3/sheet?consumer_key=" + ck + "&consumer_secret=" + cs + "&after=" + "&per_page=100";
var url = surl
Logger.log(url)
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
Logger.log(result.getResponseCode())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = SpreadsheetApp.getSheetByName(sheet);
var consumption = {};
var arrayLength = params.length;
Logger.log(arrayLength)
for (var i = 0; i < arrayLength; i++) {
Logger.log("dfsfsdfsf")
var a;
var container = [];
a = container.push(params[i]["id"]);
Logger.log(a)
a = container.push(params[i]["name"]);
a = container.push(params[i]["sku"]);
a = container.push(params[i]["price"]);
a = container.push(params[i]["tax_status"]);
a = container.push(params[i]["stock_status"]);
a = container.push(params[i]["categories"]["name"]);
a = container.push(params[i]["images"]);
a = container.push(params[i]["attributes"]["options"]);
a = container.push(params[i]["_links"]["self"]["href"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet);
temp.appendRow(container);
}
}
I have issue using google sheets calling method describe here. As i want my new API call request, i think my main problem is to select the right sheet into the spreadsheet.
Here is a copy of my spreadsheet : Woocommerce-google sheets integration

How to use POST to set the results of a SurveyJS survey?

Is it possible to use POST to set the results of a SurveyJS survey?
I can use GET to get the survey results, but I am struggling with setting.
Here is the code I use to GET the results:
urlToSurvey = "https://dxsurvey.com/api/MySurveys/getSurveyResults/surveyID?accessKey=myKey";
$.get(urlToSurvey, function(res) {
console.log(res);
});
I want to use SurveyJS to store students' progress in an open-source plugin (Adapt Learning), so I want to directly post the progress data to SurveyJS as I cannot run a stand-alone html in the plugin.
Any help is appreciated. Thanks!
You can check this file - https://github.com/surveyjs/surveyjs/blob/master/src/dxSurveyService.ts
Here is the code responsible for sending the result:
public sendResult(
postId: string,
result: JSON,
onSendResult: (success: boolean, response: any) => void,
clientId: string = null,
isPartialCompleted: boolean = false
) {
var xhr = new XMLHttpRequest();
xhr.open("POST", dxSurveyService.serviceUrl + "/post/");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
var data = { postId: postId, surveyResult: JSON.stringify(result) };
if (clientId) data["clientId"] = clientId;
if (isPartialCompleted) data["isPartialCompleted"] = true;
var dataStringify: string = JSON.stringify(data);
var self = this;
xhr.onload = xhr.onerror = function() {
if (!onSendResult) return;
onSendResult(xhr.status == 200, xhr.response);
};
xhr.send(dataStringify);
}
The required params are the postId and result json. You can get your postId from the MySurveys page of the service (https://surveyjs.io/Service/MySurveys/ note that MySurveys page requires authorization).
This is a TypeScript code, but I'm sure it can easily be converted to the JS.

StreetView Publish API JavaScript Upload photo

I am trying to upload a photo from JavaScript using the StreetView Publish API and it seems that everything i try fails ... currently i have the uploadUrl and i need to make a post request with the actual image data
this is that i ended up doing
var input = document.querySelector('input[type="file"]').files;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var xhr = new XMLHttpRequest();
xhr.open("POST", window.uploadUrl, true);
xhr.setRequestHeader("Authorization", gapi.client.getToken().token_type + ' ' + gapi.client.getToken().access_token);
xhr.setRequestHeader("Content-Type", "image/jpeg");
xhr.setRequestHeader("X-Goog-Upload-Protocol", "raw");
xhr.setRequestHeader("X-Goog-Upload-Content-Length", dataURL.length );
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
console.log(xhr);
}
}
xhr.send(dataURL);
};
reader.readAsDataURL(input[0]);
the answer i get is the following one:
Failed to load
https://streetviewpublish.googleapis.com/media/user/.../photo/...:
Response for preflight is invalid (redirect)
can anyone suggest any possible solution to this?
thanks
UPDATE
from what i see ... when i am trying to upload the image, 2 requests are generated ... both are OPTIONS and 302 status and none of them have the headers i am trying to send ... mainly the access token
var xhr = new XMLHttpRequest();
xhr.open("POST", window.uploadUrl + "?key=...", true);
xhr.setRequestHeader("Authorization", gapi.client.getToken().token_type + ' ' + gapi.client.getToken().access_token);
xhr.setRequestHeader("Authorization", gapi.client.getToken().access_token);
xhr.setRequestHeader("Content-Type", 'image/jpeg');
xhr.setRequestHeader("X-Goog-Upload-Protocol", "raw");
xhr.setRequestHeader("X-Goog-Upload-Content-Length", dataURL.length );
xhr.onreadystatechange = function() {
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
console.log(xhr);
}
}
xhr.send(dataURL);

Shopify authentication using the google app script Class OAuthConfig

I am trying to connect with my shopify shop through the google javascrip. The schema for authentication should be something similar to the one you can find on google documentation for twitter. I'am trying the following code, but I always get the error:{"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
function getInfofromshopify() {
var handle = "01-02-0316_cmt_utensili"
var urljson ="https://mysitename.myshopify.com/admin/products.json?handle="+handle;
var oAuthConfig = UrlFetchApp.addOAuthService("shopify");
oAuthConfig.setAccessTokenUrl("https://mysitename.myshopify.com/admin/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://mysitename.myshopify.com/admin/oauth/access_token");
oAuthConfig.setAuthorizationUrl("https://mysitename.myshopify.com/admin/oauth/authorize");
oAuthConfig.setConsumerKey(API_KEY);
oAuthConfig.setConsumerSecret(Shared_secret);
var options =
{
"oAuthServiceName" : "shopify",
"oAuthUseToken" : "always"
};
var response = UrlFetchApp.fetch(urljson,options);
var responsestr = response.getContentText();
var result = Utilities.jsonParse(responsestr)
}
This worked for me:
var url = "https://<YOUR_SHOP>.myshopify.com/admin/products.json";
var username = "<YOUR_SHOPIFY_API_KEY>";
var password = "<YOUR_SHOPIFY_API_PASSWORD>";
var response = UrlFetchApp.fetch(url, {"method":"get", "headers": {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)}});