How do I connect AS3.0 to a variable in js? - javascript

I've got an AS3 code that I want to assign in JavaScript as a variable like so:
var Name = ;
If I want to set a simple stylesheet I would use:
var Name = { Name.width:500 }
etc.
How do I do that in AS3?
i want to do it like so
var As3 = action script code;
i want to give a var to the actionscript so i can use it later

A SWF on a webpage can interoperate (call functions, set variables, etc) with JavaScript using ActionScript's ExternalInterface.
For example:
ExternalInterface.call("console.log", "Hello JavaScript world!");
Apparently calling eval only works in some browsers, but you can proxy the eval as noted in this answer.
ExternalInterface.call("eval", "window.foo = 'bar'");
Of course, your CSS example is very malformed... You might could:
ExternalInterface.call("eval", "document.getElementById('myDiv').style.width='50px'");
Google for more examples of using ExternalInterface to set variables, call functions, setup callbakcs, etc.

Related

Using Java Script prototype Function in a google sheets external Library

I added a prototype function to String in google sheet project, and created a new version to be referenced in another project.
Then I referenced this new library version in another project (Resources-> Libraries in the script editor).
Now I want to use this function, but execution fails as it doesn't recognized this func.
Function definition in project1:
if (!String.prototype.newStringFunc) {
String.prototype.newStringFunc = function() {
Logger.log(this.toString());
};
}
Usage in Project2:
function test()
{
var s = "Hello";
s.newStringFunc();
}
Result:
TypeError: s.newStringFunc is not a function
If the function is defined in Project2 - all good.
Other "regular" functions within Project1, are recognized and executed properly.
Is it not possible to add a prototype function to an external library?
Prototype libraries used to work on old Rhino javascript interpreter.
So, if you turn your Project2 back to old Rhino javascript interpreter for project1, it doenst matter.
It will work again.
Just Go to Menu >> Execute >> Disable Chrome V8.
I don't really know for how long the old interpreter will be available, until then, lets use it.

How to access c# variables from a JavaScript file?

I have a C# file that pulls various config settings from different config files. A JavaScript application I'm writing needs some of those settings to run. I'm having trouble bringing the C# variables into the js file. Not sure what is the best approach. They need to end up as a JS object on the page. Would adding them to a JSon object in the C# file & calling that from the JS file work? Not even sure how to do that to be honest. Any help appreciated.
You can just declare a global variable in one of your root pages (say, _layout.cshtml):
<script>
var settings = {
foo: #(IsFoo ? "true", "false"),
bar: #SomeNumber,
baz: "#ImportantString"
}
</script>
Or, if you're writing a Web API, you can just add a /settings endpoint you can query like so (Assuming you're using jQuery):
$.get("/settings", response => {
// Store the `response` in a global variable.
});
If it's an independent javascript project and .net is more of an API, you need to make an API call which will send you those config settings.
If your javascript is part of .net MVC application, i.e., you are adding your javascript through an tag at then end of a .cshtml/.aspx file, you can easily pass it through a global variable, but even then the C# code need to pass those values through Modal to the .cshtml/aspx file.
what you can do is:
var pageConfig = pageConfig || {};
pageconfig.settings = #Html.Raw(Model.Settings); // This model object is part of the C# code and my assumption is that Settings will have array of configurations.
This can also be done globally, depending upon how the C# code is written.
Assuming that when you say 'various config settings' you're referring to .NET's ApplicationSettings (defined in Visual Studio's Properties > Settings), we've done something similar, in a generic manner, as follows:
public void WriteSettings(TextWriter writer)
{
// Declare the nameSpace for the DLL you want to pull settings from
var nameSpace = "foo.Bar"
ApplicationSettingsBase properties = (System.Configuration.ApplicationSettingsBase)Activator.CreateInstance(nameSpace, string.Format("{0}.Properties.Settings", nameSpace)).Unwrap();
foreach (SettingsProperty property in properties.Properties)
{
writer.Write(string.Format("{0}=\"{1}\", property.Name, properties[property.Name]);
}
}
I've ignored a few issues in your case:
I've not bothered trying to deal with non-strings; consider looking at property.PropertyType and casting your values appropriately
I've wrapped this in a function that accepts a TextWriter; you can pass this method Response.Output

How to parse and load javascript object?

I have one js files . I load it using other javascrupt file using eval() function. I have seen eval is slow and with some other limtation. Since i need to store my JS file object in cache and use it anytime i need after apllication starts. I dont want to do eval() everytime.
Is there anyway to do it in simple way.
var evalObj;
if(evalObj) {
console.log('eval object already evaluated');
_myfunctionInJSFile_(layouts.FormatDate(startTime), threadName, level, categoryName, message);
}
else {
evalObj = eval(fs.readFileSync('./myJSFile', 'utf8'));
console.log('re evaluating object ..' );
_myfunctionInJSFile_(layouts.FormatDate(startTime), threadName, level,message);
}
myJSFile
var _sigmaAlarmHandler_ =function(args)
{
var args = Array.prototype.slice.call(arguments);
args.unshift();
console.log('Alarm : ', args);
}
Either the conditional eval is not working.
In node.js you can simple require your js-file:
var obj = require('./myJSFile');
obj.foo();
./myJSFile.js:
exports.foo = function() {
console.log('foo');
}
This file becomes a module with exported functions, that you need.
It loads once, then every require reuse already loaded module.
If it is not commonjs-compliant (i.e. using module.exports will not work), then you can run it in its own vm:
var vm = require('vm');
vm.runInNewContext(jscode,{/*globalvars*/});
where the second parameter is an object with global vars made available in the context in which the jscode is run. So if the second param is, say, {a:1,b:"foo"} then your jscode will run with the global variable a set to 1 and the global variable b set to "foo".
The jscode itself is a string that you load from a file or elsewhere.
Think of vm.runInNewContext() as "practice safe eval". Well, relatively safe, you can still do some dangerous stuff if you pass in particular vars, like process or file etc.
I used this for the declarative part of cansecurity http://github.com/deitch/cansecurity for nodejs
You can view the sample in the file lib/declarative.js
Here is the API for vm http://nodejs.org/api/vm.html
There are options to run in the same context, etc. But that is very risky.
When you actually run the code, using your example above:
_myfunctionInJSFile_(layouts.FormatDate(startTime), threadName, level,message);
you are looking to pass in 4 params: startTime, threadName, level, message and execute the function. The issue is that you cannot run the function on the current context. You need the function to be defined and run in the file. So you should have something like:
vm.runInNewContext(jscode,{startTime:layouts.FormatDate(startTime),threadName:threadName,level:level,message:message});
And then the jscode should look like
function _myfunctionInJSFile(startTime,threadName,level,message) {
// do whatever you need to do
}
// EXECUTE IT - the above vars are set by the global context provide in vm.runInNewContext
_myfunctionInJSFile(startTime,threadName,level,message);
If you prefer to define the function and have it loaded and run in this context, then just use the commonjs format.
I think i have found the answer for this.
Since my application is running in node js which uses v8 engine platform. When the application starts v8 engine caches all the code/configuration and can be used anytime.
Similarly in my code i will pre-load the JS code using eval and i will do it only once. So on next call i will return only the loaded JS code. Here i need to modify the code to load once.
But main point we have look is that in future if any body has similar requirement they can cache their JS codes using eval (thanks to v8 engine) and use it till your application is running.

referencing the html object that made the ExternalInterface.call to the javascript function called

i apologize if my terminology is off, my actionscript skills are pretty weak sauce.
so, i have some actionscript that makes a
ExternalInterface.call('someFunction');
call.
is it possible to reference the html object that made the call to someFunction directly using the ExternalInterface.call call?
Assume that the object that makes the call also has some Callbacks (via ExternalInterface.addCallback) that are accessible via javascript.
Currently:
Actionscript source
ExternalInterface.call("someFunction");
ExternalInterface.addCallback("someCallback",someASfunction);
Javascript source
function someFunction(){
document.getElementById('idOfSWFObject').someCallback();
}
I'm thinking there must be a way of:
Actionscript source
ExternalInterface.call("someFunction",THE_OBJECT_MAKING_THE_CALL);
ExternalInterface.addCallback("someCallback",someASfunction);
Javascript source
function someFunction(o){
o.someCallback();
}
once again, sorry about the terminology. tried to lace it with as many keywords for future searches.
thanks!
I guess you are talking about ExternalInterface.objectID. This property returns an id associated with flash container in object or embed tag.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html?filter_flex=4.1&filter_flashplayer=10.2&filter_air=2.en#objectID
I suggest that you should also pass the name of "someCallback" to you JS method. This way there will be no need to hardcode it in JS.
Here's an example
// Actionscript source
const jsMethodName:String = "someFunction";
const asCallbackName:String = "someCallback";
ExternalInterface.call(jsMethodName+"(document.getElementById("++")"++");");
ExternalInterface.addCallback(asCallbackName,someASfunction);
// Javascript source
function someFunction(flashId, callbackName)
{
var flashContainer = document.getElementById(flashId);
flashContainer["callbackName"]();
}
EDIT: If you really want to get a reference to flash DOM object in someFunction arguments, you may achieve it in a bit tricky way (I would rather not, but just for your interest).
// Actionscript source
const jsMethodName:String = "someFunction";
const asCallbackName:String = "someCallback";
ExternalInterface.addCallback(asCallbackName,someASfunction);
ExternalInterface.call(
"function(){"+
jsMethodName+"("+
"document.getElementById('"+ExternalInterface.objectID+"'),"+
"'"+asCallbackName+"'"+
");"+
"}"
);
// Javascript source
function someFunction(flashContainer, callbackName)
{
flashContainer[callbackName]();
}
This way you inject some JS code from flash into js. It works, but looks messy.

how to read a global javascript variable from actionscript

Given that there is a global javascript variable on my web page named myVar, how can I access the value of the variable myVar from within my flash movie using javascript?
I see plenty of examples of using external interface in order to execute javascript from actionscript, but I am unable to find examples of returning values back into the flash movie using actionscript.
Thanks in advance. I hope my question is clear enough.
ExternalInterface works by allowing JavaScript to invoke an ActionScript function in the movie, and vice-versa. You can optionally receive a return value back from the invoked function. Here's a very simple example:
JavaScript:
<script language="JavaScript">
function getMyVar()
{
return myVar;
}
</script>
Flash/AS:
import flash.external.ExternalInterface;
var result:string = ExternalInterface.call("getMyVar");
You can also provide an anonymous function that returns your global variable value to the ExternalInterface.call method as follow:
ExternalInterface.call("function(){ return myGlobalVariable; }");
I've noticed Rex M's answer is a bit incomplete.
He was right about using...
import flash.external.ExternalInterface;
var result:string = ExternalInterface.call("getMyVar");
Then in your javascript you can use
<script language="JavaScript">
function getMyVar() {
return myVar;
}
</script>
However in order to use this, the flash movie must be in an html accessed over http. Not using file://
Here is a tutorial for communicating from actionscript to javascript and vice versa.
http://www.youtube.com/watch?v=_1a6CPPG-Og&feature=plcp
You can also do this:
ExternalInterface.call("eval","getVar=function(obj){return obj}");
var yourVar:String = ExternalInterface.call("eval","getVar(JSvar)");

Categories