Add Checkbox/DropDownList in WORD using Addin JS API - javascript

I'm new to WORD ADDIN and I want to add Checkbox/DropDownList in MS WORD using Word Addin and I tried to add using Word.ContentControlType but its not helping. Can anybody tell me or provide any reference regarding it? I'm sharing my code along with the link to the official documentation of WORD ADDIN JAVASCRIPT API.
Thanks.
document.getElementById("btn-1").addEventListener("click", ()=>{
Word.run(function (context) {
var range = context.document.getSelection();
// var myContentControl = range.insertContentControl();
var myContentControl = range.insertContentControl(Word.ContentControlType.checkBox);
myContentControl.tag = 'FirstName';
myContentControl.title = 'FirstName';
myContentControl.cannotEdit = false;
// myContentControl.style = 'Heading 2';
myContentControl.insertText('');
myContentControl.appearance = Word.ContentControlAppearance.boundingBox;
context.load(myContentControl, 'id');
return context.sync().then(function () {});
});
});
https://learn.microsoft.com/en-us/javascript/api/word/word.contentcontroltype?view=word-js-preview

Thank you for reaching us! Checkbox and DropDownList content control are not supported so far by Office JS API to get or operate it. I'd recommend going to Microsoft 365 Developer Platform Ideas Forum and see if this feature has already been requested or request a new feature.

Related

Using deleteRow when passing a parameter using Google Sheets with Client-side & Server-side

I am using Google's Web Apps for this code and I am a true novice when it comes to javascript. The way it works is that the user enters an id and once they click the delete button the value is passed to the server-side. Before it deletes I want it to copy the row over to another tab (that works) and then proceed to delete the row which is not working. Thanks in advance for the help. Below is the server side code.
function removeRecord(dataInfo) {
var ss = SpreadsheetApp.openById(sheetID);
var source = ss.getSheetByName("Table");
var target = ss.getSheetByName("Deleted");
var data = source.getRange(2, 1, source.getLastRow()-1, source.getLastColumn()).getValues();
var id = data.map(function (r) { return r[0]; });
var pos = id.indexOf(dataInfo);
if (pos > -1) {
target.appendRow(data[pos]);
source.deleteRow(data[pos]);
}
}
I think that the argument of deleteRow(rowPosition) is the integer number. But, in your script, an array is used. I think that this might be the reason for your current issue. In the case of your script, how about the following modification?
From:
source.deleteRow(data[pos]);
To:
source.deleteRow(pos + 2);
Note:
From I am using Google's Web Apps, when you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
As another approach, in your script, the following modification might be able to be used. In this case, TextFinder is used. By this, the process cost might be able to be reduced a little. By the way, in this script and the above modification, it supposes that dataInfo is the valid value. Please be careful about this.
function removeRecord(dataInfo) {
var ss = SpreadsheetApp.openById(sheetID);
var source = ss.getSheetByName("Table");
var search = source.getRange("A2:A" + source.getLastRow()).createTextFinder(dataInfo).matchEntireCell(true).findNext();
if (!search) return;
var target = ss.getSheetByName("Deleted");
search.offset(0, 0, 1, source.getLastColumn()).copyTo(target.getRange(target.getLastRow() + 1, 1), { contentsOnly: true });
source.deleteRow(search.getRow());
}
Reference:
deleteRow(rowPosition)

Error when trying to edit created Document with context.application.createDocument

I am developing an office web addin, and running in Word Online.
I am trying to edit a document that I have created with context.application.createDocument. Here is the code:
Word.run(function (context) {
var myNewDoc = context.application.createDocument(base64);
context.load(myNewDoc);
return context.sync().then(function () {
myNewDoc.body.insertText('Hello World!', 'Start');
myNewDoc.open();
return context.sync();
});
});
I get this error at insertion of text / context.sync():
GeneralException The action isn’t supported in Word Online. Check the
OfficeExtension.Error.debugInfo for more information. statement: var
body=v.body;
Please help.
This error is by design. On the newly created document, you can only call open methods. All others methods are not supported which means you can't operate the newly created document.

Microsoft Sapi in Javascript - changing voices

Currently working on an implementation to use SAPI object in javascript to render some text to speech.
I have basic code which works as:
VoiceObj = new ActiveXObject("Sapi.SpVoice");
VoiceObj.Speak("hello world");
I am now looking at a way to change which voice is getting used for the TTS. From looking through the SAPI docs online, I have managed to get an object which contains the voices available, and can select them by an index.
voices = VoiceObj.GetVoices();
VoiceObj.Voice = voices.Item(1);
console.log(VoiceObj.Voice.GetDescription());
This will correctly pulls voices back, and when logged out, will give the name of the voice. The problem comes when I try and call .Speak after making a change to the voice. The javascript will just throw Automation server can't create object error and no speech is heard.
Is this the correct way for changing the voice? I can not find any other methods available which would achieve this.
var voiceObj = new ActiveXObject("Sapi.SpVoice");
//voiceObj.Speak("hello world");
var voices = voiceObj.GetVoices();
var i,n=voices.Count;
var v; //VoiceObj.Voice
for(i=0; i<n; i++){
console.log("Item "+i);
var v=voices.Item(i);
console.log(v.GetDescription());
}

How to Create Gmail Filters Programmatically?

I would like to create Gmail filters programmatically in a Chrome extension for standard Gmail users (read non Google App). Currently, thanks to those 2 (outdated) resources:
Grexit Filters API
Gmail Filter Assistant, Userscript
I have managed to develop an early prototype able to create a filter which automatically archives ("cf2_ar=true") emails received at a certain email address ("cf1_to="). However, it seems like any other "cf2" parameters used by Gmail are not valid anymore. For instance, applying a label with parameters "cf2_cat=" or "cf2_sel=" does nothing.
I know that Gmail's code is not very friendly and open when it comes to app or extension development but I would appreciate any help if some of you have any ideas, suggestions or updates regarding the current parameters used by Gmail to create filters, especially the one(s) used to apply labels to messages.
script.js (DOM end)
// Inject API into Gmail DOM
var s = document.createElement('script');
s.src = chrome.runtime.getURL('js/lib/api.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.parentNode.removeChild(s);
};
document.addEventListener('Demo_connectExtension', function(e) {
if(e.detail) {
// Gmail GLOBALS : DATA
DATA = e.detail;
user_data[0] = DATA[9]; // Id (ik)
user_data[1] = DATA[10]; // Email
user_data[2] = DATA[17][9][8]; // Locale
user_data[3] = DATA[7]; // Gmail inbox
var emailarr = user_data[1].split('#');
user_data[4] = emailarr[0] + '+do#' + emailarr[1]; // email for filter
var regex_cookie = new RegExp("GMAIL_AT=(.+?);");
if (typeof document.cookie !== 'undefined') {
// Get cookie
var gmcookie = document.cookie.match(regex_cookie)[1];
console.log('cookie:' + gmcookie);
var gmail_filter_url = 'https://mail.google.com' + user_data[3] +
'/?ui=2&ik=' + user_data[0] +
'&at=' + gmcookie +
'&view=up&act=cf&pcd=1&mb=0&rt=c';
var postdata = 'search=cf&cf1_to=' +
encodeURIComponent(user_data[4]) +
'&cf2_ar=true';
$.post(gmail_filter_url, postdata, function(gmail_response){
console.log(gmail_response);
});
}
// [...]
api.js (injected into Gmail)
'use strict';
var GLOBALS;
setTimeout(function() {
/* Send Gmail Data to my extension */
document.dispatchEvent(
new CustomEvent('Demo_connectExtension', {
detail: GLOBALS
}));
}, 1);
Actually, cf2_sel parameter does work for me. I had somewhat similar issue, described in this question and answer.
My code uses Grexit filters project and solves a sample use case:
"When a keyword is present in email content, add label, archive and set filter for this keyword"
I tested it successfully and when looking at Grexit code, 'labelas' action sets abovementioned "cf2_sel" parameter.
My sample project can be found here and provide you with means for quick testing and verification if this works for you.

Google custom search for images only

Since Google image search API is deprecated, one should use Google custom search API for this.
I've made a small example using it. My problem is I want to return google image search results only. Whereby this shows web results, and the user may switch to the image result. How can I show only the image results by default?
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'hu'});
google.setOnLoadCallback(function() {
var customSearchOptions = {
enableImageSearch: true,
imageSearchOptions: {
layout: google.search.ImageSearch.LAYOUT_CLASSIC
}
};
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
var customSearchControl = new google.search.CustomSearchControl('XXX', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
customSearchControl.setAutoCompletionId('XXX');
customSearchControl.draw('cse', options);
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
The API documentation is quite poor, it only describes how to add additional results.
Google images search is now supported in the Custom Search Engine API. See the API parameters section of this page. I'm using the API with python and for my application I just specify the parameter in the API call.
searchType = "image"
See this post on the cse blog.
EDIT: As Marc points out in his comment below, you need to click "Enable image search" in your CSE console.
Per the Google Custom Search Element Control API - documentation web site, this is possible.
https://developers.google.com/custom-search/docs/element
This is the fragment used for searching by image by default:
'defaultToImageSearch'
So I believe the full syntax for using this would be:
<script>
.
// Google custom search code, ids go here...
.
</script>
<gcse:search></gcse:search>
**<gcse:searchresults enableImageSearch="true" defaultToImageSearch="true">**
For those going through the WebExtensions tutorial, here's the updated code I used in popup.js to make it work with the new CSE functionality:
/**
* #param {string} searchTerm - Search term for Google Image search.
* #param {function(string,number,number)} callback - Called when an image has
* been found. The callback gets the URL, width and height of the image.
* #param {function(string)} errorCallback - Called when the image is not found.
* The callback gets a string that describes the failure reason.
*/
function getImageUrl(searchTerm, callback, errorCallback) {
// Google image search - 100 searches per day.
// https://developers.google.com/image-search/
// var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
// '?v=1.0&q=' + encodeURIComponent(searchTerm);
var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
'?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.items || response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
var firstResult = response.items[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.image.thumbnailLink;
var width = parseInt(firstResult.image.thumbnailWidth);
var height = parseInt(firstResult.image.thumbnailHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
Mainly it's changing the search URL (which should have searchType=image as mentioned) and the response structural references in getImageUrl, and setting up the CSE engine. Make sure your CSE has Image search turned on, and under Sites to search make sure to select Search the entire web but emphasize included sites from the options list.
I'm not 100% certain on this, but I don't think the API supports what you're trying to do. This is not at all surprising, as Google's search API's are infamous for being lacking in even basic functionality (such as the standard search API's limit of 20 results, etc). I think the fact that I'm the first person to answer this in the 3 days it's been active is another indication that this is probably just not supported (or, if it is, Google never bothered to tell anyone).
I know you're not going to like this, but I think your best option is to scrape the images out of the returned result set yourself. That's typically what people have to resort to when dealing with Google results data. Fortunately, their frontend code is remarkably consistent, so a few well-tuned regex matches and/or splits should do the trick for ya.
And yes, it's total BS that Google has provided such lousy support for this API. =)
Try adding this line:
customSearchOptions['disableWebSearch'] = true;
I tried to get a more authoritative answer in the official Google AJAX APIs group,
and it seems the answer is NO(!). Google custom search API currently does not support image search only. You can use the deprecated Google image search API instead.
check this
Try this one
customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;

Categories

Resources