Use Javascript to call method within a flash (.swf) file? - javascript

I have a flash file that contains a package "game" which has a class "Scores" and a method setValue(). I want to write some lines of Javascript that allow me to call that method. Someone directed me to this tutorial, but I am still a bit confused.
Javascript: alert("start"); var so; so = document.embeds[0];
so.addParam("allowScriptAccess","always"); import flash.external.ExternalInterface;
ExternalInterface.call("setValue[2600]");
displays an alert to tell me that it has indeed began to execute
saves the embedded flash file into a variable and sets access
imports that class
calls the method
I am not sure about how this class thing works? This is just the bits and pieces I was able to come up with from that site, but I don't really understand how it all works (but certainly hope to eventually). This is the site: http://bytes.com/topic/flash/answers/694359-how-do-i-access-flash-function-using-javascript. When I execute the code with the importation nothing happens, but the alert does come up when I don't have that statement?
If someone could elaborate on how I might call that method, I would be very thankful! :)

The code you have there is a mix of JavaScript and ActionScript.
In ActionScript, you need to register the setValue function for external use, so it can be called from JavaScript. Code for it could look something like this:
package game
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.text.TextField;
public class Scores extends Sprite
{
public var txtScore:TextField; // A textfield in the sprite
public function Scores()
{
// Register the function for external use.
ExternalInterface.addCallback("setValue", setValue);
}
private function setValue(value:Number):void
{
txtScore.text = String(value);
}
}
}
And the JavaScript could look something like this:
var so = document.embeds[0];
so.setValue(2600);

Adobe has the documentation with a lengthy but useful example here. They show the ActionScript as well as the JavaScript, and how they can interact in both ways.

Related

Why p5js skethch integrated with Vaadin won't start?

I'm trying to integrate a p5js with the Vaadin. The goal is to plug p5js library and my p5js Sketch as well into the Vaadin's view component. So I would be able to launch and render my a p5js Sketch on client side and refer to some logic on the server side.
As I am figuring out once p5js library loaded it would start automaticaly (The p5js library is a script file with a main function inside round brakets) and catch my "setup()" and "draw()" functions from sketch. And this is exactly how it works if I make an empty html page and plug scripts there with tags.
In Vaadin I used #JavaScript annotation for both scripts and start localhost but hothing happens. Sketch won't start. There is test "console.log()" inside "setup()" function it won't works off too.
Also somehow I can't reach the sketch's functions from browser's console (Neither just "setup()", nor "window.setup()", nor "p5.setup() fit) but with tiny code modification I can. If I place my sketch code inside "window.ns={// my code}" I can refer to it via "window.ns..." in the console. So I'm pretty sure sketches are loaded with page.
What am I missing?
Here is Vaadin's view class I've made (Java):
#Route(value = "/MyView")
#JavaScript("p5.js")
#JavaScript("sketch.js")
public class MyView extends VerticalLayout {
public MyView() {
}
}
Here is the Sketch's code (JavaScript):
function setup () {
console.log(`test message`);
createCanvas(400, 400);
}
function draw () {
background(220);
}
There is no any error message relevant to the issue. The console is silent.
Update:
Also it might be useful if someone experienced look at the high-levevel library code to figure out how it starts:
high-levevel library code
The content of the JavaScript is not automatically executed. You need to add JavaScript call in your view, something like.
#Route(value = "/MyView")
#JavaScript("./p5.js")
#JavaScript("./sketch.js")
public class MyView extends VerticalLayout {
public MyView() {
getElement().executeJs("setup();draw();");
}
}

How do you use multple files in a JavaScript project that will not be used as a web application? Need a single working example

I'm kind of going nuts here.
I need to start writing a stand alone non web application in JavaScript.
My problem is that I can run (using nodejs) the script just fine, but I can't split the code that I need to write among multiple files because then I don't know how to include them.
Rigth now all I want is the simplest working example of including a JS file inside another so I can use the functions defined there (or class if I so choose).
My test.js looks like this.
const { outputText } = require("./text_module.node.js");
outputText();
While my text_module.node.js looks like this:
function outputText(){
console.log("hello world");
}
My package.json looks like this:
{
"type": "text_module.node.js"
}
I have tried
Adding export before the function. It tells me export is unexpected
Using this notation: import { something } from "a_path". Anything that uses this notation will get me an "Unexpected token {" error.
The current configuration simply tells me that outputText() is not a function. So I'm out of ideas.
I don't know how else to search. I've been searching for hours on this topic and it seem that no matter where I look there is some HTML code that is needed to tie everything togeter or using another third party tool. Using jQuery loads stuff "asynchronically" which is not what I need. I want it to sequential.
Is JS just NOT suppossed to be used like other scripting languages? Otherwise I can't figure out why this is so complicated. I feel like I'm missing something big here.
If you want to use const { outputText } = require("./text_module.node.js");,
export it as module.exports = { outputText: outputText }.
In your question,
Adding export before the function. It tells me export is unexpected
Because it's an es6 thing and nodejs doesn't support all es6 features. You can refer to this answer for more details on that.

How to include plain JavaScript in a React app?

I'm trying to create a React page which includes a p5 sketch, but doing so seems to require me to rewrite standard JavaScript I would normally run in a browser to make it work as a react component.
For example, I'd like to have React serve this code to the client:
function setup() {
createCanvas(600, 600);
}
function draw() {
background(0);
}
But I can't find a way to just have React give the client a JavaScript file. Instead I have to create a component like this:
export default function(p: p5) {
p.setup = function setup() {
p.createCanvas(600, 600);
};
p.draw = function draw() {
p.background(0);
};
}
This might seem trivial but if my team and I can include code that we've already written which works outside of react without having to rewrite everything would make things much easier.
One way to solve the problem is to just place the file in the public directory of React and just serve it statically along with index.html, but I'd prefer to only give the client the file when it needs it instead of just serving every file at once. If I could just have a component import the JavaScript file and send it like it can do with images, that would be exactly what I'm looking for.
Edit: Sorry, to clarify what I meant, Node is what's actually serving things, what I want is when React renders a page it will also run JavaScript code as if it were written in a <script> tag in the HTML page.
I've solved it. Essentially I put all of the code I want to run in a file like sketch.js but surround it in a function which is exported:
export default function Sketch() {
function setup() {
createCanvas(600, 600);
}
function draw() {
background(0);
}
}
Then in app.js you can do something like:
import Sketch from './sketch';
Sketch();
That will run all of the code in that function in the client's browser.
So just an option, we do this for optionally loading certain scripts on our app. In your component on the constructor (or maybe the willMount, play around with it) create a new script tag and append that script tag to the head of you app. This will cause the script to only be run when this component is rendered (Depending on where you called the function to add the script tag). You might also have to think about removing the script tag depending on what your doing, but you get the idea.
The function would look something like this:
addScriptTag = () => {
script = document.createElement('script');
script.src = [url/path of the javascript you want to server from your node server];
// Or just set the javascript on the script tag by adding innerText and type arts
document.head.appendChild(script)
}
then do something like:
constructor() {
this.addScriptTag();
}

scala.js call external js function

I want to try using scala.js on a SalesForce project.
SalesForce automatically injects the Visualforce.remoting.Manager.invokeAction(...) function to enable querying data and doing dml.
How can I call this function from scala.js?
In the crudest sense, you could just invoke it directly from global scope using js.Dynamic, something like:
js.Dynamic.global.Visualforce.remoting.Manager.invokeAction(...)
That works for a one-off, but if you're going to be working more with this Manager, I'd probably recommend creating a Scala.js facade for the Manager, and assigning the Manager object to that -- it'll probably result in better code in the long run.
You should be able to call any exposed javascript method from scala-js using
scala.scalajs.js.eval(x: String)
Example for calling a bootbox modal:
import scala.scalajs.js.annotation.JSExportTopLevel
import scala.scalajs.js
#JSExportTopLevel("myCallBack")
protected def confirmCallback() = // do stuff
def askAQuestion(): Unit = {
js.eval("bootbox.confirm(\"Your question goes here.\", function(result) { if (result == true) { myCallBack(); }});")
}
Of course for this to work you have to include the javascript libary in your project.
Since this is a quite messy solution, you might consider writing your own facade.

Calling Java function from Rhino

Calling Javascript functions running inside Rhino from Java is easy enough - that after all is why Rhino was created. The thing I am having trouble establishing is this:
Context: I have a Phonegap CLI (v 6.3.3) Android project (API 19+) where I do a great deal of processing via loadable JavaScript running inside rhino
A Phonegap plugin - which I am creating at the same time as the actual Phonegap app - contains class called Storage which provides public, static, methods such as readFromFile(String fileName), writeToFile(String fileName,String data) etc.
What I want to be able to do is to call Storage.readFromFile etc from my loaded JavaScript code in Rhino.
Just how this should be done is not too clear to me. From the searches I have done thus far it involves using ScriptableObject.putProperty to pass the Java class in question, Storage in my case to JavaScript. However, how this should be done and then how it should be used at the JS end leaves me rather confused.
I would be most grateful to anyone here who might be able to point me in the right direction
Given that Rhino has less than 100 followers here it should perhaps come as little surprise that this question was not answered. In the mean time I have managed to find the solution myself and it turns out to be very simple. I share it below for the benefit of anyone else running into this thread.
My Storage class is very simple. It goes something like this
public class Storage
{
public static boolean haveFile(){}
public static boolean readFromFile(String fname){}
...
}
When I call Javascript from Java via Rhino I simply pass a new instance of the Storage class as the last of my function parameters
Context rhino = Context.enter();
Object[] functionParams = new Object[] {"Other parameters",new Storage()};
rhino.setOptimizationLevel(-1);
try
{
Scriptable scope = rhino.initStandardObjects();
String rhinoLog = "var log = Packages.io.vec.ScriptAPI.log;";
String code = /*Javascript code here* as shown separately below/;
rhino.evaluateString(scope, rhinoLog + code, "ScriptAPI", 1, null);
Function function = (Function) scope.get("jsFunction", scope);
Object jsResult = function.call(rhino,scope,scope,functionParams);
}
where the Javascript code is
function jsFunction(a,s)
{
//a - or a,b,c etc - here will be the "other" parameters
//s - will be the instance of the Java side Storage class passed above
//now you can do things like
s.writeToFile('fileName','fileData');
var fd = s.readFromFile('fileName');
s.dropFile('fileName');
...
}

Categories