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
Related
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
I'm trying to extract a specific value from this json file:
An example value I'm looking for is exDividendDate, fmt : 2020-09-24.
The code I've written to extract the value doesn't doesn't extract this or any other value and I'm not sure why. Any help would be greatly appreciated.
The error I get in the Google Apps Script is:
TypeError: Cannot read property 'earningsDate' of undefined (line 44,
file "Stock Database"
function callAPI(symbol) {
// Call the API
var url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/'
var modules = "?modules=calendarEvents"
var response = UrlFetchApp.fetch(url + symbol + modules);
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
console.log(data)
return JSON.parse(json)
}
function displayFinancials() {
// Load sheets
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
var modelSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Financial Ratios Model");
// Get model input data
var company = "Apple"
var symbol = "AAPL"
// call the API
var api = callAPI(symbol);
var results = api[0];
// Output the API result
var output = [company, symbol, results.exDividendDate.fmt]
console.log(output);
dataSheet.appendRow(output)
}
When I saw the JSON data, it seems that exDividendDate is callAPI(symbol).quoteSummary.result[0].calendarEvents. So how about the following modification?
From:
var results = api[0];
To:
var results = api.quoteSummary.result[0].calendarEvents;
In React Native, how do I check if a given URL is a valid image?
For example, if the url is https://stackoverflow.com/, it should return false. And if it is https://i.imgur.com/qMUWuXV.jpg, it should return true
Try this
checkValidUrl = (url) => {
//define some image formats
var types = ['jpg','jpeg','tiff','png','gif','bmp'];
//split the url into parts that has dots before them
var parts = url.split('.');
//get the last part
var extension = parts[parts.length-1];
//check if the extension matches list
if(types.indexOf(extension) !== -1) {
return true;
}
}
console.log(checkValidUrl("https://homepages.cae.wisc.edu/~ece533/images/airplane.png"));
Try this:
checkValidURLImage(){
var a = "https://i.imgur.com/qMUWuXV.jpg"; //your url
var b = ["jpeg","jpg","png","gif","raw"]; //format img
var c = a.split("."); // ["https://i", "imgur", "com/qMUWuXV", "jpg"]
console.log(b.includes(c[c.length-1]))
}
I've been reading about Javascript for 2 days now and I'm still confused. I'm familiar with HTML and CSS. My goal is to display a dynamic value on my website. The data will be from an API call using JSON.
The URL i'm using displays info like this
{
"error" : 0,
"error_message" : "-",
"amount" : 35.63000
}
What I want to do is take the "amount" variable and display it on my website. So far I have managed to jumble a bunch of code together that barely makes sense to me. I'm probably using all the wrong syntax so I will continue to try and figure this out myself. All this does it displays a static variable in "div1". What is the best way to convert the variable from the API call to show instead.
$.getJSON('https://www.amdoren.com/api/currency.php?api_key=jbqe5fH8AykJTFbnyR7Hf3d2n3KVQR&from=USD&to=THB&amount=1', function(data) {
//data is the JSON string
});
////
var $items = $('#amount')
var obj = {}
$items.each(function() {
obj[this.id] = $(this).val();
})
var json = JSON.stringify(obj);
///
var obj = [ {
"error": 0,
"error_message": "-",
"amount": 35.60000 ///THIS IS OBVIOUSLY STATIC...
}]
var tbl = $("<table/>").attr("id", "mytable");
$("#div1").append(tbl);
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td3 = "<td>" + obj[i]["amount"] + "</td></tr>";
$("#mytable").append(tr + td3);
}
I created a WCF data service which return JSON format
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
i used titanium to connect to web service to get data
var label= Titanium.UI.createLabel({
top:300
});
var data = [];
// Connecting to WCF data service
var xhr = Titanium.Network.createHTTPClient();
var theURL = 'http://localhost:4338/DataService.svc/Orders?$format=json';
var json;
xhr.onload = function (){
var json = JSON.parse(this.responseText);
};
for (var i = 0 ; i < json.length; i++)
{
data.push(json[i]);
}
label.text = data[0].OrderID;
xhr.open('Get',theURL);
what is wrong
First of all you have to be aware that HTTP requests are asynchchronous, which means although it will take some time to fetch the response (depending on the internet connection, server speed, data size etc.), the succeeding code is executed. If the request was synchronous, it would block the app and any user interaction while it loads. That is why the client provides callbacks that are fired on certain state changes.
Your code
var data = [];
// Connecting to WCF data service
var xhr = Titanium.Network.createHTTPClient();
// Just guessing, but is the $ necessary?
var theURL = 'http://localhost:4338/DataService.svc/Orders?$format=json';
// You are defining json here 'globally'
var json;
xhr.onload = function (){
// You are defining the json variable within the scope of
// the onload function, so it can't be accessed from outside
// the function. Moreover, you are overwriting json of the global scope
// within this function
var json = JSON.parse(this.responseText);
};
// At this point, json is undefined
// Moreover, this code is executed before xhr.onload fires
for (var i = 0 ; i < json.length; i++)
{
data.push(json[i]);
}
label.text = data[0].OrderID;
// Method should be GET not Get
xhr.open('Get',theURL);
How it should work
var data = [];
var theURL = 'http://localhost:4338/DataService.svc/Orders?format=json';
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function (){
// Assuming that you have a valid json response
var json = JSON.parse(this.responseText);
for (var i=0; i < json.length; i++) {
data.push(json[i]);
}
// For testing, otherwise make sure it won't break if your response is empty
label.text = data[0].OrderID;
};
xhr.open('GET', theURL);