Handle 'drop' event with Apps script for Google Doc AddOn - html

I want to handle ondrop event for Google Docs with Apps Script AddOn.
I can see that Google Docs provide drag and drop functionality by which we can easily drag images from images.google.com to google doc. I want to handle this drop event by AddOn that I am developing.
Tried finding some inbuilt way to handle drop event but google don't provide it as of now. I had tried lot of other ways like HTML5 DnD etc but as addon renders as an iframe, it is unable to access the doc html. window.parent don't help.
Any help will be appriciated

I didn't run into the same issues using the drag and drop API. It might have to do with making sure you set <base target="_top">. The script below was written in a google doc. Just drag an image from google images and it will display in the dialog box.
code.gs
function onOpen() {
var menu = DocumentApp.getUi().createMenu("Get Image");
menu.addItem("Open Dialog", "openDialog").addToUi();
}
function openDialog(){
var html = HtmlService.createHtmlOutputFromFile('index');
DocumentApp.getUi().showModelessDialog(html, "drag n drop")
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
span {
display: inline-block;
}
img {
width: 100%;
}
</style>
</head>
<body>
Drag Image Here<br>
<span><img id="img" heigth=></span>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).on('dragover', function(e) {e.preventDefault();return false;});
$(document).on('drop', function(e) {
e.preventDefault();
e.originalEvent.dataTransfer.items[0].getAsString(function(url){
var parser = document.createElement('a');
parser.href = url;
if(parser.hostname === "www.google.com"){
var src = parser.search.split("?")[1].split("&")[0].split("=")[1];
$("#img").attr("src",src);
}else{
alert("please select an image from google images")
}
});
});
</script>
</html>

Related

How can I add a horizontal scrollbar in the google sheet similar to form control scrollbar in excel?

I would like to add a horizontal scrollbar that will provide the values 0-365 based on its position and use this value for calculation.
I am creating a Gantt chart, the same as is on the page https://www.vertex42.com/ExcelTemplates/excel-gantt-chart.html
There is a horizontal scrollbar that helps "to move" with the calendar.
I have put there a number that I must change manually. I haven't found any solution on the internet.
This kind of control is simply not available natively within Google Sheets. I found a recent response from the Google Support Forums to indicate this is still the case.
If you want to build this functionality out yourself, it is actually now possible to do so, by taking full advantage of the Apps Script platform and their Google Sheets and HTML Service scripting APIs. You can create a dialog box with HTML and JS, which can have any inputs you want, including range sliders, and it can send the values back to the Google Sheet script, which can then save it to a cell. I put together a barebones test to make sure it would work, and it does:
I used Menu -> Tools -> Script Editor, and then created these two files:
Code.gs:
// Trigger dialog to be added to menu on file open
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi()
.showModalDialog(html, 'Dialog title');
}
function saveSliderVal(updatedVal){
var sheetToSaveTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Gantt');
if (!sheetToSaveTo){
sheetToSaveTo = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
}
var cellToSaveTo = sheetToSaveTo.getRange('A1:A1');
cellToSaveTo.setValue(updatedVal);
}
index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function update() {
document.getElementById('val').innerText = document.getElementById('input').value;
}
function save() {
// Call sheet function
google.script.run.saveSliderVal(parseInt(document.getElementById('input').value, 10));
}
</script>
<input id="input" type="range" min="0" max="365" onchange="update()" oninput="update()" value="0"
step="1" />&nbsp<span id="val">0</span>
<br />
<button id="save" onclick="save()">Save to Gantt</button>
</body>
</html>
Then reload the sheet after saving your script, and you should see Dialog -> Open as a new menu item. Clicking it will bring up your custom HTML.

Resize an add-on's sidebar for ease-of-use

I am trying to implement interactive pages with Google Apps Script. I've successfully opened a document in the UI sidebar, but the dimensions of the sidebar make it difficult to use:
How can the embedded sidebar page be made more attractive / easier to use?
My Google doc is here : https://docs.google.com/document/d/17AtHwUSQdci-lh7BDvXeELcpZdXr27AryHlfagRR4Hg/edit
Gode.gs
var TITLE = 'Sidebar Title';
//Here is the code.gs code:
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('==Sidebar==')
.addItem('Show Document','SideBar3')
.addToUi();
};
function SideBar3()
{
var ui = HtmlService.createHtmlOutputFromFile('ModeLessDialog').setTitle('Handler Communications');
ui.setWidth(800)
DocumentApp.getUi().showSidebar(ui);
}
//Here is the HTML file. I called it ModeLessDialog.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<iframe src="https://docs.google.com/document/d/1yb7knN941rdS-6okHQu_ZkvkgIaqXUIMioSAru9fzK4/" height="1000" width="90%"></iframe>
</body>
</html>
You can no longer change the sidebar width in Google addons. The UI had the setWidth() method earlier but it is now deprecated.
In Google Docs and Forms, sidebars now ignore the setWidth() method; they cannot be changed from the default width of 300px.
See release notes mentioning this change.

Create a Google Form in Pop up of Google Spreadsheet. Could this be done?

Reference :
Single Google Form for multiple Sheets
Re-claim :
I have a little bit hard to made my writing some good or as well to
be understanding (less english).
I have a little insight about a Google Apps Script (GAS).
I have change "MyURLDoc" and "MyIdDoc" bellow as cosinderring of
mine.
Question :
How do I make a Google Form be inside of a Pop up what I've made in Google Spreadsheet ?
Attempt 1 :
function goToURL() {
FormApp.openByUrl(//*** MyURLDoc! ***//);
}
Attempt 2 :    
Following as the reference has worte there!
function goToForm() {
var form = FormApp.openById(//*** MyIdDoc! ***//),
    formUrl = form.getPublishedUrl(),
    response = UrlFetchApp.fetch(formUrl),
    formHtml = response.getContentText(),
    htmlApp = HtmlService
.createHtmlOutput(formHtml)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Ta Daaa!')
.setWidth(500)
.setHeight(450); SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
}
Problem :
It says always like this:     " No item with the given ID could be found or You do not have permission "
Creating a Sidebar with a Google Form
I just went to an old form I have and got the embed code. I loaded into a sidebar that I had on another project and pasted the embed code which is an iframe and it loaded perfectly except for the size and I ran the form and sure enough it loaded data into the spreadsheet that contains it.
I thought I'd go ahead and add a complete example. This is a simple example which creates a form for inputting time stamped text into a spreadsheet. It's done two ways. The first technique uses standard html, javascript, JQuery and Google Script. The second technique is accomplished by just creating a form and embedding it into a simple html page. Both versions fit into the side bar and both are linked to spreadsheet pages where the text is loaded and timestamped.
Code.gs:
function onOpen()
{
SpreadsheetApp.getUi().createMenu('My Tools')
.addItem('createTextEntryForm', 'createTextEntryForm')
.addToUi();
loadSideBar();
SpreadsheetApp.getUi().createMenu('My Menu').addItem('loadSidebar', 'loadSideBar').addToUi();
}
//This loads the text into the spreadsheet for the html version of the form.
function dispText(txt)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Notes');
var ts=Utilities.formatDate(new Date(), 'GMT-6', "M/dd/yyyy HH:mm:ss");
var row=[];
row.push(ts);
row.push(txt);
sht.appendRow(row);
return true;
}
function loadSideBar()
{
var userInterface=HtmlService.createHtmlOutputFromFile('formBar');//sidebar for html and formBar for form
SpreadsheetApp.getUi().showSidebar(userInterface);
}
//This is the form
function createTextEntryForm()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var form=FormApp.create('Form On A Sidebar');
form.setDescription('Enter Your Message and Push Submit when complete.')
.setConfirmationMessage('Message Saved and TimeStamped.')
.setAllowResponseEdits(true)
.setAcceptingResponses(false)
.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
var containerLink=form.addParagraphTextItem();
containerLink.setTitle('Enter your comment now.')
.isRequired();
}
sidebar.html which is the html version of the form:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
});
function sendText()
{
var txt=$('#txt1').val();
google.script.run
.withSuccessHandler(clearText)
.dispText(txt);
}
function clearText()
{
$('#txt1').val('');
}
console.log("My code");
</script>
</head>
<body>
<textarea id="txt1" rows="12" cols="35"></textarea>
<br />
<input id="btn1" type="button" value="submit" onClick="sendText();" />
</body>
</html>
formBar.html is where the form is embedded:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<iframe src="FormURL?embedded=true#start=embed" width="300" height="550" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
</body>
</html>
This is what the spreadsheet and sidebars look like:

Create dropdown menu within a popup window

I have a list of records in multiple sheets (same workbook).
I currently have a dropdown menu within my googlesheet where if you select one of the records it will delete the row with that record.
However, I would like to give the option to either move it to another sheet or delete it. I was trying to use UiApp but then found out alot of the options are deprecated and that now I have to use HTMLService.
So what I'm looking to do is, once I select a record, have a popup that has two options.
Option 1 : a Move option (button) with a dropdown of the names of the other sheets within the workbook that will then move that record to that sheet
Option 2 : Delete the record
Option 3 : Cancel.
Is this possible? and if so, would someone be able to guide me to the right direction or a similar example so I can try and figure out how to get that going?
You can try creating a Custom dialogs
A custom dialog can display an HTML service user interface inside a Google Docs, Sheets, or Forms editor.
Custom dialogs do not suspend the server-side script while the dialog is open. The client-side component can make asynchronous calls to the server-side script using either the google.script API for HTML-service interfaces or server handlers for UI-service interfaces.
Code.gs
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Custom Menu')
.addItem('Show dialog', 'showDialog')
.addToUi();
}
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'My custom dialog');
}
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select>
<option>Delete</option>
<option>Move</option>
</select>
</body>
</html>
With that, try reading about HTML Service: Communicate with Server Functions
google.script.run is an asynchronous client-side JavaScript API that allows HTML-service pages to call server-side Apps Script functions. The following example shows the most basic functionality of google.script.run — calling a function on the server from client-side JavaScript.
Here is a sample code for form:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input name="myFile" type="file" />
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
Hope this helps!

I need two things to happen with one link

i have a link in place, which opens a popup window that gives you instructions on how to add this page to your bookmarks. Now i also want the link to fire a conversion in adwords when it gets clicked. For that i have a script from google which i tried ti combine with the existing link, but i think i did something wrong since no conversion gets fired in my test. Please help me here:
<html>
<head>
</head>
<body>
<a id="bookmarkme" href="#" rel="sidebar" onClick="goog_report_conversion" title="bookmark this page">Bookmark this page!</a>
<!-- Google Code for People who added website to their bookmarks Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = XXXXXXXX;
w.google_conversion_label = "COldCKSHnl8Q2cu9ywM";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
window.google_is_call = true;
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
<script type="text/javascript">
$(function() {
$("#bookmarkme").click(function() {
// Mozilla Firefox Bookmark
if ('sidebar' in window && 'addPanel' in window.sidebar) {
window.sidebar.addPanel(location.href,document.title,"");
} else if( /*#cc_on!#*/false) { // IE Favorite
window.external.AddFavorite(location.href,document.title);
} else { // webkit - safari/chrome
alert('Please press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D in order to add this page to your bookmarks, you can also use your browsers bookmark menu to do that.');
}
});
});
</script>
</body>
</html>
Setting up an onclick handler for conversions
First, make sure you selected Click instead of Page load from the "Tracking event" section of the "Advanced tag settings" in Part I of the instructions above. Your conversion tag should look like something this:
<!-- Google Code for Add to Cart Conversion Page
In your html page, add the snippet and call goog_report_conversion
when someone clicks on the chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = 12345678;
w.google_conversion_label = "abcDeFGHIJklmN0PQ";
w.google_conversion_value = 13.00;
w.google_conversion_currency = "USD";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
Now that you (or the person in charge of your website) have the conversion tracking tag, you're ready to paste. Here's how:
Go to the page on your website that shows the clickable button or link. Then open up the HTML code so you can edit it.
Find the body tags (<body></body>) of the page, then paste the code snippet you generated in AdWords between those two tags.
Adjust the HTML code to add the onclick handler. The particular onclick command you use will depend on how the link or button is displayed on your site: text link, image, or button.
Here's some sample code close up:
HTML before conversion tracking code (Sample only. Don't use in your website's code.)
<html>
<head>
<title>Sample HTML File</title>
</head>
<body>
This is the body of your web page.
</body>
</html>
Use the following command if the link is shown as:
a text link
<body>
<!-- Below is a sample link for a file download.
You need to replace the URL for the file and the
DOWNLOAD NOW text with the text you want to hyperlink. -->
<a onclick="goog_report_conversion
('http://www.example.com/whitepapers/a.pdf')"
href="#" >DOWNLOAD NOW</a>
</body>
</html>
an image
<!-- Below is a sample image for a file download.
Replace download_button.gif with your
button image and the document URL with your file's URL. -->
<body>
<img src="download_button.gif" alt="Download Whitepaper"
width="32" height="32"
onClick="goog_report_conversion
('http://www..pdf')"/>
</body>
</html>
For the tracking to work, you'll need to make sure you include both the tag and the appropriate onclick tags from one of the examples above. This tells AdWords to record a conversion only when a customer clicks on a chosen link or button.
Alright, it works the following way:
<a onclick="goog_report_conversion
('')" id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark this page!</a>