I try to develop an app to create user in mikrotik user manager via api. And I also tried JavaScript in the terminal by using following command:
$node script name.js
That is working and a user created.
Then I tried to run that JavaScript by on click html button. Then JavaScript doesn't run and no user crated. Code follows:
<html>
<head>
</head>
<body>
<button type = "button" onclick="conn();">Try it</button>
<script type="text/javascript">
var api = require('mikronode');
var connection = new api('192.168.5.1','admin','xxxxxx');
connection.connect(function conn() {
conn.closeOnDone(true); // All channels need to complete before the connection will close.
var actionChannel=conn.openChannel();
// These will run synchronsously
actionChannel.write(['/tool/user-manager/user/add','=username=tiran','=password=123456','=customer=admin']); // don't care to do anything after it's done.
actionChannel.write(['/tool/user-manager/user/create-and-activate-profile','=customer=admin','=numbers=tiran','=profile=general']); // don't care to do anything after it's done.
//actionChannel.write('/tool/user-manager/user/print',function(chan) {
//chan.on('done',function(data) {
//packets=api.parseItems(data);
//packets.forEach(function(packet) {
//alert('done');
//alert('user: '+JSON.stringify(packet));
//console.log('user: '+JSON.stringify(packet));
//});
//listenChannel.close(); // This should call the /cancel command to stop the listen.
//});
//});
actionChannel.close(); // The above commands will complete before this is closed.
});
</script>
</body>
</html>
That code is for NodeJS, you cannot run in directly on the browser as JavaScript
Related
I have a dialog flow that will require a user to upload a file/files. I would like to prompt the user and have them click on a button to open a file browse window to select the file they want to upload. I do not want to use the file chooser in the WebChat window text entry box (Users find this confusing). Is this possible? I saw in the documentation for v3 that there is a AttachmentPrompt dialog. However in the documentation for v4 I only see it mentioned in a one liner here... https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0 however other than that which sounds promising there appears to be no documentation on this functionality.
Thanks for any help you can provide!
PromptAttachment does not define client side rendering, or client side file upload code. In order to have the WebChat control respond to a custom button, you will need to provide an Attachment Middleware for the Web Chat control, and have the bot send a custom attachment type.
Custom Attachment:
private class FileUpload : Attachment
{
public FileUpload()
: base("application/uploadAttachment") { }
}
Replying with FileUpload attachment:
var reply = activity.CreateReply("Upload a File");
reply.Attachments.Add(new FileUpload());
await connector.Conversations.SendToConversationAsync(reply);
Page hosting Web Chat:
<!DOCTYPE html>
<html>
<body>
<div id="webchat" />
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://unpkg.com/react#16.5.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.5.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/react-redux#5.0.7/dist/react-redux.min.js"></script>
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<script>
function uploadFile() {
document.querySelector('[title="Upload file"]').click();
}
</script>
<script type="text/babel">
var chatbot = new WebChat.createDirectLine({
token: 'YourToken',
webSocket: true,
});
const attachmentMiddleware = () => next => card => {
switch (card.attachment.contentType) {
case 'application/uploadAttachment':
return (<button type="button" onClick={uploadFile}>Upload file</button>);
default:
return next(card);
}
};
WebChat.renderWebChat({
directLine: chatbot,
botAvatarInitials: 'Bot',
attachmentMiddleware,
}, document.getElementById('webchat'));
</script>
</body>
</html>
Is there a way to write a google apps script so when ran, a second browser window opens to www.google.com (or another site of my choice)?
I am trying to come up with a work-around to my previous question here:
Can I add a hyperlink inside a message box of a Google Apps spreadsheet
This function opens a URL without requiring additional user interaction.
/**
* Open a URL in a new tab.
*/
function openUrl( url ){
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}
This method works by creating a temporary dialog box, so it will not work in contexts where the UI service is not accessible, such as the script editor or a custom G Sheets formula.
You can build a small UI that does the job like this :
function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
var app = UiApp.createApplication().setHeight(50).setWidth(200);
app.setTitle("Show URL");
var link = app.createAnchor('open ', href).setId("link");
app.add(link);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
If you want to 'show' the URL, just change this line like this :
var link = app.createAnchor(href, href).setId("link");
EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).
EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!
EDIT :
below is an implementation using html service.
function testNew(){
showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}
function showAnchor(name,url) {
var html = '<html><body>'+name+'</body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}
There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.
window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)
openUrl.html
<!DOCTYPE html>
<html>
<head>
<base target="_blank">
<script>
const url1 ='https://stackoverflow.com/a/54675103';
const winRef = window.open(url1);
winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
window.onload=function(){document.getElementById('url').href = url1;}
</script>
</head>
<body>
Kindly allow pop ups</br>
Or <a id='url'>Click here </a>to continue!!!
</body>
</html>
code.gs:
function modalUrl(){
SpreadsheetApp.getUi()
.showModalDialog(
HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
'Opening StackOverflow'
)
}
Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.
It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers
Deprecated. The UI service was deprecated on December 11, 2014. To
create user interfaces, use the HTML service instead.
The example in the HTML Service linked page is pretty simple,
Code.gs
// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
A customized version of index.html to show two hyperlinks
<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>
Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html file in your project and using Stephen's code from above, just convert it into an HTML doc.
<!DOCTYPE html>
<html>
<base target="_top">
<script>
function onSuccess(url) {
var a = document.createElement("a");
a.href = url;
a.target = "_blank";
window.close = function () {
window.setTimeout(function() {
google.script.host.close();
}, 9);
};
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
window.document.body.append(a);
}
event.initEvent("click", true, true);
a.dispatchEvent(event);
} else {
a.click();
}
close();
}
function onFailure(url) {
var div = document.getElementById('failureContent');
var link = 'Process';
div.innerHtml = "Failure to open automatically: " + link;
}
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
</script>
<body>
<div id="failureContent"></div>
</body>
<script>
google.script.host.setHeight(40);
google.script.host.setWidth(410);
</script>
</html>
Then, in your Code.gs script, you can have something like the following,
function getUrl() {
return 'http://whatever.com';
}
function openUrl() {
var html = HtmlService.createHtmlOutputFromFile("index");
html.setWidth(90).setHeight(1);
var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}
I liked #Stephen M. Harris's answer, and it worked for me until recently. I'm not sure why it stopped working.
What works for me now on 2021-09-01:
function openUrl( url ){
Logger.log('openUrl. url: ' + url);
const html = `<html>
<a id='url' href="${url}">Click here</a>
<script>
var winRef = window.open("${url}");
winRef ? google.script.host.close() : window.alert('Configure browser to allow popup to redirect you to ${url}') ;
</script>
</html>`;
Logger.log('openUrl. html: ' + html);
var htmlOutput = HtmlService.createHtmlOutput(html).setWidth( 250 ).setHeight( 300 );
Logger.log('openUrl. htmlOutput: ' + htmlOutput);
SpreadsheetApp.getUi().showModalDialog( htmlOutput, `openUrl function in generic.gs is now opening a URL...` ); // https://developers.google.com/apps-script/reference/base/ui#showModalDialog(Object,String) Requires authorization with this scope: https://www.googleapis.com/auth/script.container.ui See https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes
}
https://developers.google.com/apps-script/reference/base/ui#showModalDialog(Object,String) Requires authorization with this scope: https://www.googleapis.com/auth/script.container.ui See https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes
I need help with Google App Script on a Google Sheet and an Html form. I just cannot get them to connect properly. The form has a text box and two buttons. The user enters a name in the text box and press the start button. The start button records time to a variable. When finished, the user presses finish. The finish button records the time and processes the text box and start button. This info is sent back to the Google App Script to be written to the Sheet. I would like to use an AJAX or JQuery call, but it doesn't seem to be working. Need a little help getting the nice form working. I have tried doGet(e) and doGet() functions, but those aren't working. I have tried lots of different versions of the code. This isn't my final html form, but it has the same point. If I click the button, AJAX should return something to the Google App Script after processing. New to Google App Scripting and need help. Thanks!
code.gs
function doGet(e) {
var result = "";
try {
result = "Hi" + e.queryString;
//should write to the spreadsheet the information here
} catch (f) {
result= "Error" + f.toString();
}
result=JSON.stringify({"result":result});
return ContentService
.createTextOutput( "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
//where does HtmlService.createHtmlOutput('index.html') go?
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Make an AJAX call to Google Script
function callGoogleScript() {
var url = "https://script.google.com/macros/s/" my script id "/exec";
var data = { name: "Tom", city: "Nowhere" };
var request = jQuery.ajax({
url:url+encodeURIComponent(data),
method: "GET",
dataType: "jsonp"
});
}
// print the returned data
function ctrlq(e) {
console.log(e.result)
}
</script>
</head>
<body>
<button id="test" name="test" onclick="callGoogleScript()">Test</script>
</body>
</html>
Edit: This is for a Web App.
I wrote the following HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>
<body>
<script src='http://localhost:3000?callback=mycallbackFunction'> </script>
<script>
function mycallbackFunction(data) {
alert('here');
alert (data['a']);
}
</script>
</body>
</html>
As you can see, the script tag includes a JSONP request to a remote server.
In addition, I wrote the following node.js file and ran it as a server:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.jsonp({'a': 'blabla'});
});
app.listen(3000);
After I had run the node.js file and opened the browser with the html page, I expected to see a pop-up window of alert. But, no. I didn't see anything.
The Network Tab in Developer Tools shows that the request has been accepted:
Do you know how to resolve it?
You need to swap the order of your <script> elements.
Explanation:
Express is correctly serving a script that looks like myCallbackFunction({'a': 'blabla'}), which is exactly what you hoped for. However, this script runs immediately, and myCallbackFunction has yet to be defined, so nothing happens. Then, in the next <script> block, you define myCallbackFunction, but this is useless, since the (failed) call has already happened in the previous <script>.
Also, you have a case mismatch on the C in mycallbackFunction -- make sure the capitalization agrees between the callback parameter and the name of your function.
The solution is to switch the order of both script tags:
<body>
<script>
function mycallbackFunction(data) {
alert('here');
alert (data['a']);
}
</script>
<script src='http://localhost:3000?callback=mycallbackFunction'> </script>
</body>
In case of Edge browser say Browser One, passing a custom argument to second Browser.
if I pass a string it is available in the second window. But, if I pass an object (say XMLDocument) in the second window, I could not serialzetoString.
var myWin = window.open(...);
myWin.customArg = 'string parameter' // Works
myWin.customArg = xmlObject // Doesnt Work
in the second window,
new XMLSerializer().serializeToString(xmlDoc)
throws xml parser exception.
Can any one help in resolving this?
Same code works fine for Chrome.
Edit - Sample code of Parent Window is here -
<html>
<head>
<script type="text/javascript">
function OpenWindow()
{
var objXML = '<SelectedCharts><Chart ColumnNo="1" ChartName="E0PK" GroupName="test" OrderNo="1" /></SelectedCharts>';
var xmlDoc = new DOMParser().parseFromString(objXML,'text/xml');
var dialog = window.open("Child_Window.htm", "title", "width=550px, height= 350px,left=100,top=100,menubar=no,status=no,toolbar=no");
dialog.dialogArguments = xmlDoc ;
dialog.opener = window;
}
</script>
</head>
<body>
<span>Passing an XML Object to the child window:</span>
<input type="button" value="Open Popup" onclick="OpenWindow()" />
</body>
</html>
And the sample code of Child window is here -
<html>
<head>
<script type="text/javascript">
function onBodyLoad()
{
alert(new XMLSerializer().serializeToString(window.dialogArguments));
}
</script>
</head>
<body onload="onBodyLoad()">
<span>This is child window.</span>
</body>
</html>
The code snippet shown in the question works fine for Chrome browser. And to pass the context to another window in case of Edge browser, follow the below method.
declare a global variable and set it in the parent window
And, access the varable in the child window using window.opener.
And sample code is provided in Pass custom arguments to window.open in case of Edge browser