[Solved] My Basic call to a JavaScript does nothing

Java, C++, C#, Delphi... - Using the UNO bridges
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

[Solved] My Basic call to a JavaScript does nothing

Post by owlbrudder »

I have been wrestling with this for a while. I have finally reached a position where my Basic code is 'finding' the JavaScript, but nothing happens when I make the call. Stepping through the debugger, I cannot step into the routine to see what it is doing, so I am programming blind. I would be very grateful if someone could show me what I am doing wrong. "8-)

The purpose of the macro is to run a regular expression over the string passed in and return the resulting string to the Basic macro.

Here is my Basic code:

Code: Select all

Sub CallJavaScript
    Dim oScriptProvider, oScript
    Dim aParams(), aOutParamIndex(), aOutParam()
    Dim MyArray(2)
    Dim MyParam As String
    MyArray(0)="John O'Brien"
    MyArray(1)="'"
    MyArray(2)="''"
    oScriptProvider = ThisComponent.getScriptProvider()
    oScript = oScriptProvider.getScript( "vnd.sun.star.script:abpaJavaScripts.jsRegExp.js?language=JavaScript&location=document" )
	oScript.invoke( MyArray, aOutParamIndex, aOutParam)
	subInspect(oScript)
End Sub
And here is the JavaScript:

Code: Select all

/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

/* Applies strReplace to all instances of strRegexp in strSearch and returns the result */
function jsRegExp(strSearch, strRegexp, strReplace) {
	var strRetVal;
	strRetVal = strSearch.replace(strRegexp, strReplace);
	return strRetVal;
}
Just because I have been programming since 1982 does not mean I am immune to making idiotic mistakes, so don't hesitate to tell me if I have in this case!

Cheers,
Doug
Last edited by owlbrudder on Fri Aug 11, 2017 2:37 am, edited 1 time in total.
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
robleyd
Moderator
Posts: 5055
Joined: Mon Aug 19, 2013 3:47 am
Location: Murbko, Australia

Re: My Basic call to a JavaScript does nothing

Post by robleyd »

Caveat; I have never used Starbasic, and it has been a day or six since I used JS. So if I get this wrong ...

As I see it, your JS simply replaces the substring ' with the substring '' in the string passed to it - John O'Brien and returns the new string. What I can't see is anywhere in your Basic where you assign the returned value from the JS.

Would you not need something like:

Code: Select all

ReturnVal = oScript.invoke( MyArray, aOutParamIndex, aOutParam)
Cheers
David
OS - Slackware 15 64 bit
Apache OpenOffice 4.1.15
LibreOffice 24.2.1.2; SlackBuild for 24.2.1 by Eric Hameleers
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Thanks for replying David. Yes, I need to assign the result - doh! (Slaps forehead.)

I changed the relevant line to:

Code: Select all

	strResult = oScript.invoke( MyArray, aOutParamIndex, aOutParam)
and stepped through the code again. Sadly, the strResult value is 'undefined'.

I am sure I am calling the code with the correct information, but I'm still prepared to be told I am wrong.

Where I have a problem is understanding how my JavaScript return value bubbles back up the stack to my Basic code. Do I need to return the value in some other (unexplained) way? Is my JavaScript supposed to populate the aOutParamIndex and aOutParam empty arrays I am passing from Basic and, if so, how does JavaScript 'see' them?

Sigh. Wisdom only comes with age, but all too often age arrives unaccompanied. "8-[
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
robleyd
Moderator
Posts: 5055
Joined: Mon Aug 19, 2013 3:47 am
Location: Murbko, Australia

Re: My Basic call to a JavaScript does nothing

Post by robleyd »

Looking at this topic suggests that the ReturnVal should be populated just as if you were calling a function; here and here there is some information on the additional arguments; like FJCC, my head swims looking at them.

I assume you did declare strResult - I don't know how Basic handles un-declared vars.

Have you tried MRI to monitor your script? [Tutorial] Introduction into object inspection with MRI
 Edit: Also found this which may shed some light? Or may drive you to $beverage_of_choice. 
Cheers
David
OS - Slackware 15 64 bit
Apache OpenOffice 4.1.15
LibreOffice 24.2.1.2; SlackBuild for 24.2.1 by Eric Hameleers
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Thanks very much David - I will read and digest your links.

PS: Yes, in this example I am trying to replace a single single-quote with two single-quotes as part of a routine to feed an SQL statement into PostgreSQL.

PPS: Love your icon! "8-D
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
robleyd
Moderator
Posts: 5055
Joined: Mon Aug 19, 2013 3:47 am
Location: Murbko, Australia

Re: My Basic call to a JavaScript does nothing

Post by robleyd »

Tux the spam hunter :-)
Cheers
David
OS - Slackware 15 64 bit
Apache OpenOffice 4.1.15
LibreOffice 24.2.1.2; SlackBuild for 24.2.1 by Eric Hameleers
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Tux the spam hunter
I thought he was Tux the Window Cleaner ... "8-)

Your links cover some ground I have already traversed and the really interesting ones are no longer accessible because the ooo forum is no more. Never mind. I will keep slogging on in the hope something will spring to mind.

Many thanks for your input.
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

I am now at the stage where I am able to call my javascript, but it does nothing. The script is in the form of a function which expects the three arrays ( arystrInputParameters(), aryintOutParamIndex(), aryvarOutParam() ) to be passed to it by Basic. I have no way of knowing whether the function is actually being called and I have no way of knowing what is happening to the three arrays passed. I do know that nothing is being returned.

I also do not know where to look next. "8-[

Drowning not waving ...
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
robleyd
Moderator
Posts: 5055
Joined: Mon Aug 19, 2013 3:47 am
Location: Murbko, Australia

Re: My Basic call to a JavaScript does nothing

Post by robleyd »

My next step would be to put a line in the JS that writes something to the screen? or wherever to confirm the JS is being called. Assuming this can be done within Basic?

If you care to post your current scripts, someone might be able to give them a run and try and diagnose. Maybe even I might sully my hands with an attempt at Basic :lol:
Cheers
David
OS - Slackware 15 64 bit
Apache OpenOffice 4.1.15
LibreOffice 24.2.1.2; SlackBuild for 24.2.1 by Eric Hameleers
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Thanks David. I will try calling a dialog box showing my input parameters and see what explodes. "8-)

In the meantime, here are the Basic and Javascript macros as they currently stand:

Code: Select all

Sub CallJavaScript
    Dim oScriptProvider, oScript
    Dim aryintOutParamIndex(0) As Integer, aryvarOutParam(0) As String
    Dim arystrInputParameters(2)
    Dim strResult As String
    
    arystrInputParameters(0)="John O'Brien"
    arystrInputParameters(1)="'"
    arystrInputParameters(2)="''"
    
    oScriptProvider = ThisComponent.getScriptProvider()
    
    oScript = oScriptProvider.getScript( "vnd.sun.star.script:jsRegExp.jsRegExp.js?language=JavaScript&location=user" )
    strResult = oScript.invoke( arystrInputParameters, aryintOutParamIndex, aryvarOutParam )
End Sub

Code: Select all

/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

/* Applies strReplace to all instances of strRegexp in strSearch and returns the result */
function jsRegExp(strSearch, strRegexp, strReplace) {
	var strRetVal;
	strRetVal = strSearch.replace(strRegexp, strReplace);
	return strRetVal;
}
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

I have made a little progress. At the bottom of the javascript, I have added the line:

Code: Select all

jsRegExp(strSearch, strRegexp, strReplace);
This at least is provoking a response, although it is not entirely helpful:
BASIC runtime error.
An exception occurred
Type: com.sun.star.script.provider.ScriptFrameworkErrorException
Message: "strSearch" is not defined..
At least I now know I have to include a statement calling my function, but I still don't know how to access the data being passed by the Basic routine. One step forward, two steps back ...
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
RoryOF
Moderator
Posts: 34586
Joined: Sat Jan 31, 2009 9:30 pm
Location: Ireland

Re: My Basic call to a JavaScript does nothing

Post by RoryOF »

There is discussion on this (or related problem) in this thread
viewtopic.php?f=44&t=54483

One could rewrite the Javascript function in BASIC.

Search and Replace with regular expressions in OO BASIC is dealt with in
http://wiki.services.openoffice.org/w/i ... ldid=91519
Apache OpenOffice 4.1.15 on Xubuntu 22.04.4 LTS
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Thanks for the reply, RoryOF.

I have read the links you provided and they add to my knowledge, but they don't answer the core question of how to access, in my javascript macro, the data passed by Basic. I am able to invoke my javascript by executing

Code: Select all

strResult = oScript.invoke( arystrInputParameters, aryintOutParamIndex, aryvarOutParam )
(Having set up the appropriate variables, of course), but I cannot figure out how to use the data contained in arystrInputParameters when it arrives at the javascript macro.

I have seen countless examples of Basic calling javascripts that don't use passed data, but none that do.

Circles. Round. Going in. "8-/
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
RoryOF
Moderator
Posts: 34586
Joined: Sat Jan 31, 2009 9:30 pm
Location: Ireland

Re: My Basic call to a JavaScript does nothing

Post by RoryOF »

Might this be the old programming problem of call by value or call by reference?
Apache OpenOffice 4.1.15 on Xubuntu 22.04.4 LTS
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

It could be involved with that. The immediate problem is I don't know how to look for the information from within the javascript ie: what is the name of the variable/package/stream/? arriving from the Basic macro?
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
RPG
Volunteer
Posts: 2250
Joined: Tue Apr 14, 2009 7:15 pm
Location: Netherlands

Re: My Basic call to a JavaScript does nothing

Post by RPG »

Hello

It is me not so clear what you want do. It is clear to me it is difficult. I have the idea that Incorporated RegEx engine: How to get full access? (View topic) • Apache OpenOffice Community Forum is not so difficult as what you try now.

Romke
LibreOffice 7.1.4.2 on openSUSE Leap 15.2
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Thanks Romke - I will read the link you provided.

I am trying to pass data to a javascript. The script needs to process the data and return a value. I have everything working except for receiving the data into the javascript. I don't know how to get at the data passed in the call.

Still trying, but in the case of the RegExp your solution may be better.

Kind regards,
Doug

--------------------------------------

The link you provided shows how to manually replace the search term with the replacement term, but I am trying to write what is effectively a one-liner to perform the global search and replace without writing extensive Basic code. If I can get at the data I am passing from Basic, the problem is solved. "8-)
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
Villeroy
Volunteer
Posts: 31269
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: My Basic call to a JavaScript does nothing

Post by Villeroy »

oScript = oScriptProvider.getScript( "vnd.sun.star.script:abpaJavaScripts.jsRegExp.js?language=JavaScript&location=document" )
Your JS code resides in the document?

The following is a working function call to Python's soundex which is stored in <user_profile>/Scripts/python/pyCalc

Code: Select all

REM Keep a global reference to the ScriptProvider, since this stuff may be called many times:
Global g_MasterScriptProvider

REM Specify location of Python script providing the cell functions
REM We insert the function name between the URL_MAIN and URL_Args
Const URL_Main = "vnd.sun.star.script:pyCalc|sheetFunctions.py$"
Const URL_Args = "?language=Python&location=user"

Function getMasterScriptProvider()
   if NOT isObject(g_MasterScriptProvider) then
      oMasterScriptProviderFactory = createUnoService("com.sun.star.script.provider.MasterScriptProviderFactory")
      g_MasterScriptProvider = oMasterScriptProviderFactory.createScriptProvider("")
   endif
   getMasterScriptProvider = g_MasterScriptProvider
End Function

Function SOUNDEX(s$, optional iLen%)
   sURL = URL_Main & "soundex" & URL_Args
   oMSP = getMasterScriptProvider()
   oScript = oMSP.getScript(sURL)
   if isMissing(iLen) then
      i = 4
   else
      i = cInt(iLen)
   endif
   x = oScript.invoke(Array(s,i),Array(),Array())
   SOUNDEX = x
End Function
SOUNDEX in Python:

Code: Select all

def soundex(name, len=4):
    """ soundex module conforming to Knuth's algorithm
        implementation 2000-12-24 by Gregory Jorgensen
        public domain
    """

    # digits holds the soundex values for the alphabet
    digits = '01230120022455012623010202'
    sndx = ''
    fc = ''

    # translate alpha chars in name to soundex digits
    for c in name.upper():
        if c.isalpha():
            if not fc: fc = c   # remember first letter
            d = digits[ord(c)-ord('A')]
            # duplicate consecutive soundex digits are skipped
            if not sndx or (d != sndx[-1]):
                sndx += d

    # replace first digit with first alpha character
    sndx = fc + sndx[1:]

    # remove all 0s from the soundex code
    sndx = sndx.replace('0','')

    # return soundex code padded to len characters
    return (sndx + (len * '0'))[:len]
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Hi Villeroy.

Yes, my JS was in the document, but I have since moved it to the 'user' library.

Marshalling the parameters in Basic is working as per your code, but there are obvious differences in the scripts.

In your Python code, the initial statement "def soundex(name, len=4):" is directly using the parameters passed from Basic - no?

From https://ask.libreoffice.org/en/question ... ic/#110819, Ratslinger is saying I need to read my input from the zero-th element of an array named 'ARGUMENTS', namely 'event = ARGUMENTS[0]', then parcel out the three parameters I am interested in from that sub-array.

Sadly, this is not working for me - yet! If I use Ratslinger's code unchanged, I get an error at the line "strSearch = event[0];" - "Cannot read property "0" from undefined". If I change Ratlinger's first line to "event = ARGUMENTS;", I get an error at the line "strRetVal = strSearch.replace(strRegexp, strReplace);" - ""Cannot read property "replace" from undefined.".

Either way, it seems my javascript is not receiving into ARGUMENTS[0] the values I am trying to pass OR and more likely, I am totally wrong in my usage.

I am continuing to hack away in the hope of making a breakthrough, but in the meantime I do appreciate all the help I am getting.

I will set up a call to a python script such as you have given, to see if at least that much works. I am quite happy to write my script in Python, which I assume has equivalent RegExp functionality built in.

My worst case scenario would be that my version of LO (LibreOfficeDev Version: 5.3.3.0.0+) is not compatible with calling scripts in this way. "8-[
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
Villeroy
Volunteer
Posts: 31269
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: My Basic call to a JavaScript does nothing

Post by Villeroy »

The function takes a string and an integer with 4 as default value and =SOUNDEX("owlbrudder") entered into a sheet returns "O416".
Why don't you ask Ratslinger who wrote the tutorial?
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
RPG
Volunteer
Posts: 2250
Joined: Tue Apr 14, 2009 7:15 pm
Location: Netherlands

Re: My Basic call to a JavaScript does nothing

Post by RPG »

Hello

I think the API capable to handle it. Sure it is capable to search with regexp. You need a little BASIC for replacing. When you study the API for textsearch you can find more possibillities. in [Solved] Searching in a textbox (View topic) • Apache OpenOffice Community Forum I have post once an example how to use it.

Romke

Code: Select all

'*******************************************
sub callRegExSubst
dim targetStr 
dim sOrg
dim searchForStr 
dim replaceStr
dim flag
flag = com.sun.star.util.SearchAlgorithms.REGEXP 

targetStr="Romke die werkt in Beekbergen en woonten in  en  woooonten Apeldoorn"
searchForStr="wo{2,4}n"
replaceStr="WOON"


sOrg=targetStr
msgbox RegExSubst(targetStr, searchForStr, replaceStr, flag) &  chr(13) & sOrg

targetStr="Romke die werkt Roooomke in Beekbergen en woonten in  en  woooonten Apeldoorn"
searchForStr="Ro{1,4}mke"
replaceStr="XXXX"

sOrg=targetStr
msgbox RegExSubst(targetStr, searchForStr, replaceStr, flag) &  chr(13) & sOrg

targetStr="Romke die werkt Roooomke in Beekbergen en woonten in  en  woooonten Apeldoorn"
searchForStr="^Ro{1,4}mke"
replaceStr="XXXX"

targetStr="Romke die werkt Roooomke in Beekbergen en woonten in  en  woooonten Apeldoorn Roomke"
searchForStr="Ro{1,4}mke$"
replaceStr="XXXX"


sOrg=targetStr
msgbox RegExSubst(targetStr, searchForStr, replaceStr, flag) &  chr(13) & sOrg

end sub



Function RegExSubst(targetStr as string, searchForStr as string, replaceStr as string, flags as integer) As String
dim iStartPos
iStartPos=0 ' Start from the beginning

Dim options as new com.sun.star.util.SearchOptions
'options.algorithmType = com.sun.star.util.SearchAlgorithms.ABSOLUTE
options.algorithmType = flags
options.searchString=searchForStr

  ts = CreateUnoService("com.sun.star.util.TextSearch")
  ts.setOptions(options)
  r = ts.searchForward(targetStr, 0, Len(targetStr))
do while  r.subRegExpressions=1
	iChangeChar=(r.endOffset(0) - r.startOffset(0))
	mid (targetStr,(r.startOffset(0)+1),iChangeChar,replaceStr)
	iStartPos= (r.startOffset(0))+len(replaceStr)-1
	r = ts.searchForward(targetStr, iStartPos, Len(targetStr))
loop
RegExSubst = targetStr
end function
LibreOffice 7.1.4.2 on openSUSE Leap 15.2
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Villeroy wrote:Why don't you ask Ratslinger who wrote the tutorial?
Thanks Villeroy. Ratslinger is helping me on the other thread. So far, I have copied and pasted his working code and it still fails on my system. I suspect my installation has something screwy, but I will keep bashing away. It's a shame debugging the JavaScript is so hard from LO.
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

RPG wrote:I think the API capable to handle it. Sure it is capable to search with regexp. You need a little BASIC for replacing.
Thanks for replying RPG. I appreciate your reply with its extensive code and will adopt it if I cannot get JavaScript to do the job for me, however maintaining your Basic code is a bigger task than maintaining this JavaScript:

Code: Select all

event = ARGUMENTS[0];

strSearch = event[0];
strRegexp = event[1];
strReplace = event[2];

var strFixedIt = jsRegExp(strSearch, strRegexp, strReplace);

eval(strFixedIt);

function jsRegExp(strSearch, strRegexp, strReplace) {
    var strRetVal;
    strRetVal = strSearch.replace(strRegexp, strReplace);
    return strRetVal;
}
My aim is to be able to call parameter-driven JavaScript macros from Basic, not just perform RegExp substitutions. I can successfully invoke macros that do not require input, but cannot (yet) pass variables from Basic to JavaScript. :crazy:
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Making some progress. The following script returns the correct result to Basic:

Code: Select all

event = ARGUMENTS[0];

strSearch = "John O'Brien";
strRegexp = "'";
strReplace = "''";
jsRegExp(strSearch, strRegexp, strReplace);

/*var strFixedIt = jsRegExp(strSearch, strRegexp, strReplace);

eval(strFixedIt);*/

function jsRegExp(strSearch, strRegexp, strReplace) {
    var strRetVal;
    strRetVal = strSearch.replace(strRegexp, strReplace);
    return strRetVal;
}
Still can't pass variables into JavaScript though, which is now all that remains to solve. "8-)
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
Villeroy
Volunteer
Posts: 31269
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: My Basic call to a JavaScript does nothing

Post by Villeroy »

It is possible to write macros in JavaScript.
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Villeroy wrote:It is possible to write macros in JavaScript.
Thanks very much for your continuing support. Yes, I have succeeded in invoking JavaScript from Basic. All that is missing now is the ability to get JavaScript to 'see' the variables I pass from Basic. Ratslinger posted some code that works on his machine but fails on mine. I am continuing to debug as far as I can and will post again when I have something useful to report.
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
User avatar
Villeroy
Volunteer
Posts: 31269
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: My Basic call to a JavaScript does nothing

Post by Villeroy »

I mean, you could perhaps replace the Basic code with JavaScript. This requires that you enable Java; any Java from your distribution should be right. Then enable it via Tools>Options>Advanced...
After restarting the office suite, you should be able to call Tools>Macros>Organize>JavaScript...
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: My Basic call to a JavaScript does nothing

Post by owlbrudder »

Thanks Villeroy and everyone for the help. I have finally got it all working. To help anyone else trying to pass variables to JavaScript, this is what works for me:

Basic code:

Code: Select all

Sub CallJavaScript
    Dim oScriptProvider, oScript
    Dim aryintOutParamIndex(0) As Integer, aryvarOutParam(0) As String
    Dim arystrInputParameters(3)
    Dim strResult As String
    
    arystrInputParameters(0)="John O'Brien"
    arystrInputParameters(1)="'"
    arystrInputParameters(2)="''"
    arystrInputParameters(3)="ig"
    
    oScriptProvider = ThisComponent.getScriptProvider()
    
    oScript = oScriptProvider.getScript( "vnd.sun.star.script:abpaJavaScripts.jsRegExp.js?language=JavaScript&location=user" )
    'oScript = oScriptProvider.getScript( "vnd.sun.star.script:Highlight.ShowDialog.js?language=JavaScript&location=share" )
	strResult = oScript.invoke( arystrInputParameters, aryintOutParamIndex, aryvarOutParam )
	Print strResult
End Sub
JavaScript code:

Code: Select all

strSearch = new String(ARGUMENTS[0]);
strRegexp = new String(ARGUMENTS[1]);
strReplace = new String(ARGUMENTS[2]);
strModifiers = ARGUMENTS[3];

jsRegExp(strSearch, strRegexp, strReplace, strModifiers);

function jsRegExp(strSearch, strRegexp, strReplace, strModifiers) {
    var strPatt = new RegExp(strRegexp, strModifiers);
    var strRetVal;
    strRetVal = strSearch.replace(strPatt, strReplace);
    return strRetVal;
}
A few useful notes:
  • These functions replace a single single-quote with two single-quotes as a fix to allow single-quotes in values to be accepted by PostgreSQL
    The array sent from Basic in the first parameter to the call is seen by JavaScript is the array named ARGUMENTS
    String values extracted from ARGUMENTS are not JavaScript String objects unless coerced to be such eg strSearch = new String(ARGUMENTS[0]);
    The call new RexExp(strRegexp, strModifiers) expects the second parameter to NOT be a String object eg strModifiers = ARGUMENTS[3];
    The last three lines of the JavaScript above could probably be collapsed into one - I leave that as an exercise for the reader.
Again, many thanks to all for the help.

Cheers,
Doug
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
RPG
Volunteer
Posts: 2250
Joined: Tue Apr 14, 2009 7:15 pm
Location: Netherlands

Re: [Solved] My Basic call to a JavaScript does nothing

Post by RPG »

Hello

I do understand your problem as you want change a single quote in two singles quotes. I can understand you want learn also maybe how to call javasript from BASIC.
Maybe for your information StarBASIC does have the function replace, you can not find a description. Maybe for more information:

Code: Select all

Sub CallJavaScript
    Dim MyArray(2)
    MyArray(0)="John O'Brien"
    MyArray(1)="'"
    MyArray(2)="''"
print replace(MyArray(0),MyArray(1),MyArray(2))
    
end sub

Code: Select all

Sub CallJavaScript2
    Dim MyArray(2)
    MyArray(0)="John O'Brien"
    MyArray(1)="'"
    MyArray(2)="''"
print join(split(MyArray(0),MyArray(1)),MyArray(2))
end sub
Romke
LibreOffice 7.1.4.2 on openSUSE Leap 15.2
owlbrudder
Posts: 93
Joined: Tue Nov 08, 2016 8:04 am

Re: [Solved] My Basic call to a JavaScript does nothing

Post by owlbrudder »

RPG wrote:StarBASIC does have the function replace
Thank you very much, Romke. I had no idea there was that function available - it is exactly what I was looking for originally! At least I now know how to pass parameters to JavaScript macros from StarBASIC, so my time has not been wasted. I really must find a list of all the functions built into StarBASIC - there are probably heaps of useful things lurking there that I have not found yet.

Kind regards,
Doug
LibreOffice Version: 5.3.3.0
Fedora 26 Linux x86_64
Core i7, 8Gb
Post Reply