Good morning I wanted help for a code that can use a logical value example:
`` `
function provaIf2(){
var A2=SpreadsheetApp.getActive().getRange('A2').getValue();
var C4=SpreadsheetApp.getActive().getRange('C4').getValue();
if(A2=="") SpreadsheetApp.getActive().getRange('B2').activate();
else if(A2<C4) Print the sheet
else if(A2==C4) Print the sheet
else SpreadsheetApp.getActive().getRange('B3').activate();
}
If you want to print a document using Apps Script, you will have to use Google Cloud Print.
As explained in this article here, you will have to create an Apps Script project in which you include the OAuth2 library. Then you need to get the Google Cloud Print service, send the request and last but not least, print the document.
The below code snippet is used to print the document with the desired options:
function printGoogleDocument(docID, printerID, docName) {
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR",
vendor_id: "Color"
},
duplex: {
type: "NO_DUPLEX"
}
}
};
var payload = {
"printerid" : printerID,
"title" : docName,
"content" : DriveApp.getFileById(docID).getBlob(),
"contentType": "application/pdf",
"ticket" : JSON.stringify(ticket)
};
Reference: Automatically Print Files Placed in Drive with Google Cloud Print and Apps Script.
Related
I'm trying to use the microsoftTeams Javascript library in my Personal Tab in my Teams App. The app is written in cshtml and plain javascript.
I'm able to access the microsoftTeams object itself in my javascript file.
Ex: The following snippet works fine:
microsoftTeams.getContext(async (context) =>
userid = context.userObjectId
);
However I need to integrate the camera/gallery into my workflow in the personal tab. I was following the instructions as per this documentation : https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/device-capabilities/mobile-camera-image-permissions.
I'm facing an issue where-in the media object is undefined inside the microsoftTeams context.
The following snippet is how I'm trying to use the selectmedia api of the sdk.
function takePhotos() {
var listOfSelectedImages = new Array();
var imageProp = {
sources: [microsoftTeams.media.Source.Camera, microsoftTeams.media.Source.Gallery],
startMode: microsoftTeams.media.CameraStartMode.Photo,
ink: false,
cameraSwitcher: false,
textSticker: false,
enableFilter: true,
};
var mediaInput = {
mediaType: microsoftTeams.media.MediaType.Image,
maxMediaCount: 10,
imageProps: imageProp
};
microsoftTeams.media.selectMedia(mediaInput, function (error, attachments) {
if (error) {
if (error.message) {
alert(" ErrorCode: " + error.errorCode + error.message);
}
else {
alert(" ErrorCode: " + error.errorCode);
}
}
if (attachments)
{
// code for using atttachments here
}
});
}
I'm getting an error in both the browser and mobile client at this line microsoftTeams.media.Source.Camera, saying media is undefined.
I have included the teams.min.js file in the .layout.cshtml as follows.
<script src="https://statics.teams.cdn.office.net/sdk/v1.11.0/js/MicrosoftTeams.min.js" integrity="sha384-SCVF3m7OvDKnfAilUzYn2yozEvBeP8n/Oq0yTH8VUI70J4AzrqR70jzjdQ6DI8s2" crossorigin="anonymous"></script>
Is there something else I need to include for me to be able to access the media object?
Adding answer from comment section for more visibility:
The issue occurred due to conflicting javascript package version. Its resolved now.
I'm trying to create a file in the File Cabinet and write to it in a Client Script. Checking the API reference, I see that all the File objects are Server-side only.
Does that mean you can't create and write to a file in a Client script? I tried to use the code in my Client script anyway, but got the error:
Fail to evaluate script: {"type":"error.SuiteScriptModuleLoaderError","name":"{stack=[Ljava.lang.Object;#59c89ae9, toJSON=org.mozilla.javascript.InterpretedFunction#5a4dd71f, name=MODULE_DOES_NOT_EXIST, toString=org.mozilla.javascript.InterpretedFunction#1818dc3c, id=, message=Module does not exist: N/file.js, TYPE=error.SuiteScriptModuleLoaderError}","message":"","stack":[]}
When I tried to save it in NetSuite as the script file. Does the above mean that the N/File object can't be loaded in a Client script?
Can I write to a file in a Client script?
Create a Client Script - this Script will contain the function to call the Suitelet and pass along information from the current record/session if needed.
function pageInit{
//required but can be empty
}
function CallforSuitelet(){
var record = currentRecord.get();
var recId = record.id;
var recType = record.type
var suiteletURL = url.resolveScript({
scriptId:'customscriptcase3783737_suitelet',// script ID of your Suitelet
deploymentId: 'customdeploycase3783737_suitelet_dep',//deployment ID of your Suitelet
params: {
'recId':recId,
'recType':recType
}
});
document.location=suiteletURL;
}
return {
CallforSuitelet : CallforSuitelet,
pageInit : pageInit
}
Create a Suitelet - this script will create the file
function onRequest(context) {
var requestparam = context.request.parameters;
var recId = requestparam.recId; //the same name of the fields specified in url.resolveScript parameters from Client Script
var recType = requestparam.recType;
var objRecord = record.load({
type: record.Type.___,//insert record type
id: recId
});
var content = 'Insert Content Here';
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report-1.1.dtd\">\n";
xml += "<pdf>\n<body font-size=\"12\">\n<h3>Sample PDF</h3>\n";
xml += "<p></p>";
xml += content;
xml += "</body>\n</pdf>";
context.response.renderPdf({xmlString: xml});
}
return {
onRequest: onRequest
}
As you've already discovered, server-only modules can't be called from client-side scripts directly, but this can be done via a Suitelet. You will need to decide how the Suitelet does it's work. An example of the principal at work can be found here and here
So I've looked and looked and looked at different answers on StackExchange and other web forums and I still don't understand this.
I've got a .json file that contains the information from an excel document.
I want to display it on a web browser -> the easiest way to do this seems to be writing it in html.
How do I open the JSON file with html?? I'm happy with having the entire JSON file displayed on the html script but I would love to be able to set is as a variable and pull things out of it like a normal JSON object.
I have the code below for making a table which is what I want to do - but the real JSON object is in a separate file.
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language="javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }
],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }
]
}
var i = 0
document.writeln("<table border='2'><tr>");
for(i=0;i<books.Pascal.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i=0;i<books.Scala.length;i++)
{
document.writeln("<td>");
document.writeln("<table border='1' width=100 >");
document.writeln("<tr><td><b>Name</b></td><td width=50>"
+ books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width=50>"
+ books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
To clarify: The above code works great; but I want to do it with the contents of a .json file saved on my local drive.
Thanks in advance.
I see that you didn't include the jquery tag, so I'll provide a couple of vanilla javascript solutions:
If the file is located at an accesible directory, you can pull the data like this:
Define your JSON object as follows:
Original:
[{ "name" : "John", "date" : "01-27-2014" }]
Modified into javascript:
var data = '[{ "name" : "John", "date" : "01-27-2014" }]';
And save it to a plain text document named mydata.json.js, for example (the double extension has nothing to do with the content itself).
So it becomes a valid javascript file and you can load it on your html like this:
<script src="mydata.json.js"></script>
And you can use your data var on your HTML normally.
Or use this if you don't have the document locally or the above approach is too makeshifty for you. Refer to this question. Quoting:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (success) {
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
Update:
You can create a global var, e.g. data, to store the retrieved JSON and redefine the function as follows:
if (xhr.readyState === 4 && xhr.status === 200) {
data = JSON.parse(xhr.responseText); // This now contains the JSON object.
}
Note that xhr.responseText is the raw JSON string and the JSON.parse(…) functions returns a javascript collection with the data of that JSON.
You need to pull JSON using AJAX.
This will require you to have web server running, as some browsers, e.g. Chrome will block requests to local resources. Also have in mind that AJAX & JSON request will work only within the same domain (same origin policy), or you will have to use JSONP.
If you can use jQuery (hence it's an easiest way), look here: http://api.jquery.com/jquery.getjson/
$.getJSON( "test.json", function( data ) {
$.each( data, function( key, val ) {
// do something
});
});
Hope it helps!
You can do this without the need for ajax by using a server side language such as PHP. You can include the raw JSON into a Javascript variable.
Below is an example of including the file with PHP:
<script>
//JSON included via PHP
var books = <?php include('books.json'); ?>;
</script>
The file "books.json" would contain your raw JSON information:
{ "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }
],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }
]
}
I have loaded an https page on Amazon.co.uk and I wish to display use 'GM xmlhttpRequest' to request the price of an item on a linked page.
What I’ve been doing so far
I tried to use an iFrame to display the window:
var prodLinks = $("td.product_description a:contains('View Amazon Product Page')");
if (prodLinks.length) {
var iframeSrc = prodLinks[0].href;
iframeSrc = iframeSrc.replace (/http:\/\//, "https://")
$("body").append ('<iframe id="gmIframe" src="' + iframeSrc + '"></iframe>');
$("#gmIframe").css ( {
"position": "absolute",
"bottom": "1em",
"left": "2em",
"height": "25%",
"width": "84%",
"z-index": "17",
"background": "#00FF00"
} );
}
The problem with this approach is, that whilst it works, the contents of the iFrame is too cluttered, so I cannot see what I need to, at a glance.
The stuff I want to see
Let us suppose that the linked page is https://www.amazon.co.uk/gp/product/B001AM72BM/
The relevant HTML snippet from the aforementioned page:
<tr id="actualPriceRow">
<td id="actualPriceLabel" class="priceBlockLabelPrice">Price:</td>
<td id="actualPriceContent"><span id="actualPriceValue"><b class="priceLarge">£2.85</b></span>
<span id="actualPriceExtraMessaging">
How, exactly, can I use GM xmlhttpRequest to get the page
Background : I’m using something similar to GreaseMonkey
This is for Greasekit on Fluid.app (which is very old, but I must using it). You probably don’t even need to know that as it’s very similar to Greasekit. So, for the purposes of this question, you can just pretend it is.
My attempt at answer
I would try:
GM_xmlhttpRequest({
method: "GET",
url: "https://www.amazon.co.uk/gp/product/B001AM72BM/",
onload : function(response) {
// do something with the result here
document.getElementByClass(‘priceLarge').innerHTML = response.responseText;
}
});
Use jQuery to parse the response from GM_xmlhttpRequest, and unlike for an iframe, you don't need to rewrite the URL to SSL.
So:
Rather than add an iframe, add a node that will contain your price.
Grab the product URL as before.
Fetch the URL with GM_xmlhttpRequest.
Use jQuery to find the .priceLarge node.
Write the contents of that node to the node created in step 1.
The complete code, with some UI and error handling, looks like this. I tested it on your sample page and it works.
var prodLinks = $("td.product_description a:contains('View Amazon Product Page')");
if (prodLinks.length) {
//--- Make a place to put the price.
$("td.buybox table td.v_prod_box_topleft").append (
'<p id="gmPriceResult">Fetching...</p>'
);
GM_xmlhttpRequest ( {
method: 'GET',
url: prodLinks[0].href,
onload: getItemPrice,
onabort: reportAJAX_Error,
onerror: reportAJAX_Error,
ontimeout: reportAJAX_Error
} );
}
function getItemPrice (resp) {
/*--- Strip <script> tags and unwanted images from response
BEFORE parsing with jQuery. Otherwise the scripts will run and the
images will load -- wasting time and bandwidth and increasing risk
of complications.
*/
var respText = resp.responseText.replace (/<script(?:.|\n|\r)+?<\/script>/gi, "");
respText = respText.replace (/<img[^>]+>/gi, "");
var respDoc = $(respText);
//-- Now fetch the price node:
var priceNode = respDoc.find (".priceLarge:first");
if (priceNode.length) {
$("#gmPriceResult").text (priceNode.text () );
}
else {
$("#gmPriceResult").text ("Price not found!");
}
}
function reportAJAX_Error (resp) {
alert ('Error ' + resp.status + '! "' + resp.statusText + '"');
}
The question is very simple. How to get number of video views with YouTube API?
The task is simple but I would like to use that query on large number of videos very often. Is there any way to call their Youtube API and get it? (something like facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com)
I think, the easiest way, is to get video info in JSON format. If you want to use JavaScript, try jQuery.getJSON()... But I prefer PHP:
<?php
$video_ID = 'your-video-ID';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views;
?>
Ref: Youtube API - Retrieving information about a single video
You can use the new YouTube Data API v3
if you retrieve the video, the statistics part contains the viewCount:
from the doc:
https://developers.google.com/youtube/v3/docs/videos#resource
statistics.viewCount / The number of times the video has been viewed.
You can retrieve this info in the client side, or in the server side using some of the client libraries:
https://developers.google.com/youtube/v3/libraries
And you can test the API call from the doc:
https://developers.google.com/youtube/v3/docs/videos/list
Sample:
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}
Authorization: Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent: Google APIs Explorer
Response:
200 OK
- Show headers -
{
"kind": "youtube#videoListResponse",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"id": "Q5mHPo2yDG8",
"kind": "youtube#video",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
"statistics": {
"viewCount": "36575966",
"likeCount": "127569",
"dislikeCount": "5715",
"favoriteCount": "0",
"commentCount": "20317"
}
}
]
}
Version 2 of the API has been deprecated since March 2014, which some of these other answers are using.
Here is a very simple code snippet to get the views count from a video, using JQuery in the YouTube API v3.
You will need to create an API key via Google Developer Console first.
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key={{YOUR-KEY}}', function(data) {
alert("viewCount: " + data.items[0].statistics.viewCount);
});
</script>
Here is a small code snippet to get Youtube video views from URL using Javascript
Demo of below code
function videoViews() {
var rex = /[a-zA-Z0-9\-\_]{11}/,
videoUrl = $('input').val() === '' ? alert('Enter a valid Url'):$('input').val(),
videoId = videoUrl.match(rex),
jsonUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json',
embedUrl = '//www.youtube.com/embed/' + videoId,
embedCode = '<iframe width="350" height="197" src="' + embedUrl + '" frameborder="0" allowfullscreen></iframe>'
//Get Views from JSON
$.getJSON(jsonUrl, function (videoData) {
var videoJson = JSON.stringify(videoData),
vidJson = JSON.parse(videoJson),
views = vidJson.entry.yt$statistics.viewCount;
$('.views').text(views);
});
//Embed Video
$('.videoembed').html(embedCode);}
Why using any api key to retrieve a portion of public html!
Simplest unix command line demonstrative example, using curl, grep and cut.
curl https://www.youtube.com/watch?v=r-y7jzGxKNo | grep watch7-views-info | cut -d">" -f8 | cut -d"<" -f1
Yes, it get the full html page, this loss has no meaning against the countless advantages.
You can use this too:
<?php
$youtube_view_count = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json'))->entry->{'yt$statistics'}->viewCount;
echo $youtube_view_count;
?>
Using youtube-dl and jq:
views() {
id=$1
youtube-dl -j https://www.youtube.com/watch?v=$id |
jq -r '.["view_count"]'
}
views fOX1EyHkQwc
Use the Google PHP API Client: https://github.com/google/google-api-php-client
Here's a little mini class just to get YouTube statistics for a single video id. It can obviously be extended a ton using the remainder of the api: https://api.kdyby.org/class-Google_Service_YouTube_Video.html
class YouTubeVideo
{
// video id
public $id;
// generate at https://console.developers.google.com/apis
private $apiKey = 'REPLACE_ME';
// google youtube service
private $youtube;
public function __construct($id)
{
$client = new Google_Client();
$client->setDeveloperKey($this->apiKey);
$this->youtube = new Google_Service_YouTube($client);
$this->id = $id;
}
/*
* #return Google_Service_YouTube_VideoStatistics
* Google_Service_YouTube_VideoStatistics Object ( [commentCount] => 0 [dislikeCount] => 0 [favoriteCount] => 0 [likeCount] => 0 [viewCount] => 5 )
*/
public function getStatistics()
{
try{
// Call the API's videos.list method to retrieve the video resource.
$response = $this->youtube->videos->listVideos("statistics",
array('id' => $this->id));
$googleService = current($response->items);
if($googleService instanceof Google_Service_YouTube_Video) {
return $googleService->getStatistics();
}
} catch (Google_Service_Exception $e) {
return sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
return sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
}
YouTube Data API v3 URL Sample
Source Link
https://www.googleapis.com/youtube/v3/videos?key=[YOUR_API_KEY_HERE]&fields=items(snippet(title,tags,channelTitle,publishedAt),statistics(viewCount))&part=snippet,statistics&id=[VIDEOID]
look at yt:statistics tag.
It provides viewCount, videoWatchCount, favoriteCount etc.
Here an example that I used in my TubeCount app.
I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.
var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[#yt:name='default'](#url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(#countHint)))";
var channel = "wiibart";
$.ajax({
url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
success: function(data){
var len = data.feed.entry.length;
for(var k =0; k<len; k++){
var yt = data.feed.entry[k];
v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
}
}
});
Here is a simple function in PHP that returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API
//Define a constant so that the API KEY can be used globally across the application
define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');
function youtube_video_statistics($video_id) {
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return $views;
}
//Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
echo youtube_video_statistics('YOUTUBE_VIDEO_ID');
I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.
PHP JSON
$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);
First go through this one by uncommenting
//var_dump(json);
and get views count as:
$vcounts = $json->{'items'}[0]->{'statistics'}->{'viewCount'};
You can use JQuery, don't forget to replace Your-Api-Key string from the code below, follow the link to find your own Api key google developers console
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videospart=statistics&id=Qq7mpb-hCBY&key=Your-Api-Key', function(data) {
console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);
});
</script>
This probably is not what you want but you could scrap the page for the information using the following:
document.getElementsByClassName('watch-view-count')[0].innerHTML