i have this javascript code:
<script type="text/javascript">
$(document).ready(function() {
$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');
</script>
My code works fine so far but i thought to load this javascript code inside an AS3.
Is there any possibility to make it happen? To write inline javascript code inside my flash;
I found this code but i dont know how to implement
import flash.external.ExternalInterface;
var someVarInAS : String = 'foo';
var someOtherVarInAS : int = 10;
var jsXML : XML =
<script type="text/javascript">
var someVarInJS = '{$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');}';
var someOtherVarInJS = '{$('#login').fadeIn();}';
<![CDATA[
alert( 'this comes from flash: ' + someVarInJS + ', ' + someOtherVarInJS );
]]>
</script>;
ExternalInterface.call( "function js_" + ( new Date().getTime() ) + "(){ " + jsXML + " }" );
Can anyone help me to do this?
Here's a link to an example to show how ExternalInterface works
https://dl.dropboxusercontent.com/u/15551758/eitest.zip
What's happening is that once the Flash object is loaded on the page, it uses
ExtenalInterface.call();
to call a javascript function that's been registered on the page that the swf is on. In the case of the example:
ExternalInterface.call('toJS', 'flash text');
calls the javascript function toJS and sends one argument, a string "flash text".
The opposite direction is supported as well. Calling a function on the flash object and passing in arguments will send them to flash. You register ExternalInterface callbacks with:
ExternalInterface.addCallback(callback_name, flash_function_to_call);
In the example, we register in flash a callback:
ExternalInterface.addCallback("fromJS", this.fromJS);
that listens for an event from javascript called fromJS and calls an internal function fromJS. For the example, I've added a textbox on the stage to visualize the data coming in from javascript.
Please let me know if this answers your question or if you need more explanation.
Edit:
If you must inject javascript, you can pass in a function that does the injection as the first parameter of ExternalInterface.call:
var inject:String = "function(){var body = document.getElementsByTagName('body')[0], testNode = document.createElement('div'); testNode.innerHTML = 'This is a test'; body.appendChild(testNode);}";
ExternalInterface.call(inject);
But I'd recommend against it. Keeping languages separate will lead to more concise and easier to debug code.
Related
This question asks for a way to open a new window using window.open and then inject it with a script. It was not possible because of cross-domain security issues.
However, my problem is that I want to do the exact same thing, except from the same domain to the same domain. Is this possible?
Note that .write does not solve this problem because it wipes all the html from the page first.
You can do something like this:
var theWindow = window.open('http://stackoverflow.com'),
theDoc = theWindow.document,
theScript = document.createElement('script');
function injectThis() {
// The code you want to inject goes here
alert(document.body.innerHTML);
}
theScript.innerHTML = 'window.onload = ' + injectThis.toString() + ';';
theDoc.body.appendChild(theScript);
This also seems to work:
var theWindow = window.open('http://stackoverflow.com'),
theScript = document.createElement('script');
function injectThis() {
// The code you want to inject goes here
alert(document.body.innerHTML);
}
// Self executing function
theScript.innerHTML = '(' + injectThis.toString() + '());';
theWindow.onload = function () {
// Append the script to the new window's body.
// Only seems to work with `this`
this.document.body.appendChild(theScript);
};
And if for some reason you want to use eval:
var theWindow = window.open('http://stackoverflow.com'),
theScript;
function injectThis() {
// The code you want to inject goes here
alert(document.body.innerHTML);
}
// Self executing function
theScript = '(' + injectThis.toString() + '());';
theWindow.onload = function () {
this.eval(theScript);
};
What this does (Explanation for the first bit of code. All examples are quite similar):
Opens the new window
Gets a reference to the new window's document
Creates a script element
Places all the code you want to 'inject' into a function
Changes the script's innerHTML to load said function when the window
loads, with the window.onload event (you can also use addEventListener). I used toString() for convenience, so you don't have to concatenate a bunch of strings. toString basically returns the whole injectThis function as a string.
Appends the script to the new window's document.body, it won't actually append it to the document that is loaded, it appends it before it loads (to an empty body), and that's why you have to use window.onload, so that your script can manipulate the new document.
It's probably a good idea to use window.addEventListener('load', injectThis.toString()); instead of window.onload, in case you already have a script within your new page that uses the window.onload event (it'd overwrite the injection script).
Note that you can do anything inside of the injectThis function: append DIVs, do DOM queries, add even more scripts, etc...
Also note that you can manipulate the new window's DOM inside of the theWindow.onload event, using this.
Yes...
var w = window.open(<your local url>);
w.document.write('<html><head>...</head><body>...</body></html>');
Here's a trick I use, it uses query strings, and is client side. Not perfect but it works:
On the sending page, do:
var javascriptToSend = encodeURIComponent("alert('Hi!');");
window.open('mypage.html?javascript=' + javascriptToSend);
Replace mypage.html with your page. Now on the receiving page, add:
(location.href.match(/(?:javascript)=([^&]+)/)[1])&&eval(decodeURIComponent(location.href.match(/(?:javascript)=([^&]+)/)[1]));
You'll have to do some back-and forth to make sure this works.
If you HAVE PHP you can use this more reliable solution on the receiving page:
eval(decodeURIComponent(<?=$_GET['javascript'] ?>));
I think this is kind of unusual, but this is what I came to.
I have a .net application that generates html + js page.
I have a thing called Unit that is kind of assembly of different html elements and has artificial events onlaod and onunload.
function DisplayableUnit(content, onload_js, onunload_js)
{
this.onload_js = onload_js; //different functions calls like "f1(); f2();"
this.onunload_js = onunload_js;
this.content = content; //string of html tags
}
function loadUnitTo(elem_id, unit)
{
var elem = document.getElementById(elem_id);
if (elem)
elem.innerHTML = unit.content;
if (unit.onload_js)
;//how to execute it?
}
Many sites says that eval is bad and unsafe thing. But is that the only choice?
I need pure JS solution without any third party things.
You can execute it as a function like this:
var theInstructions = "alert('Hello World'); var x = 100",
F=new Function (theInstructions);
return(F());
Copied from this stackoverflow thread ;)
I'm teaching students how to write JavaScript, so I've got this on the page:
<textarea name="PgmJS">console.log(1);</textarea>
<script id="PgmJS">
</script>
What I'd like to do is:
$('textarea[name=PgmJS]').on('keyup',PgmJSKeyUp);
function PgmJSKeyUp() {
$('#PgmJS').text('function init() {' + $(this).val() + '}');
init();
}
But the browser is saying that init() is not defined.
It doesn't work this way, you need the evil eval:
function PgmJSKeyUp() {
eval($(this).val());
}
You could also use Function, setTimeout or setInterval (if you clear it), which are as evil as eval when used with strings.
Or, if you really want to use <script> element,
function PgmJSKeyUp() {
var $s = $('<script type="text/javascript">');
$s.text($(this).val());
$('body').append($s);
}
But keep in mind that JS code inside <script> elements is only executed when they are added to the document.
That's because you're specifying the init function inside the textarea's text property - which by default, does not get picked up by the browser's JS compiler.
You will need to define the init function as normal JS code, and execute the custom JS code inside it. I smell an eval() coming on (ugh!) :|
I have a method that looks like this
function endcall_click(leadid) {
document.location = '#Url.Action("index","dispo",new{id=leadid})/';
}
Of course it doesn't work because it treats "leadid" as a server side variable but I want to inject the javascript variable passed into the method.
I tried wrapping lead id in but that didn't work.
function endcall_click(leadid) {
document.location = '#Url.Action("index","dispo",new{id="<text>leadid</text>"})/';
}
Any ideas?
You can't inject javascript variable to a script that is evaluated at the server simply because at the moment this script executes and generates the output this variable hasn't yet come to existence. The only way to achieve this is to manipulate the resulting string:
function endcall_click(leadid) {
document.location = '#Url.Action("index", "dispo")/' + leadid;
}
The drawback is that this assumes manipulating the routes in javascript and if you decide to change them on the server the code might break.
I finally found the solution (*.vbhtml):
<script type="text/javascript">
function razorsyntax() {
/* Double */
#(MvcHtmlString.Create("var szam =" & mydoublevariable & ";"))
alert(szam);
/* String */
var str = '#stringvariable';
alert(str);
}
</script>
I have a flash movie that requires some JavaScript from an include file but I'd like to be able to embed it anywhere without requiring a script tag.
Is there a way to include an external JavaScript file using the ExternalInterface library so I can call the methods in the JavaScript include file later?
Thanks!
Not many people realize it, but you can write inline Javascript in your .as files, and even pass in values, like so:
var someVarInAS : String = 'foo';
var someOtherVarInAS : int = 10;
var jsXML : XML =
<script type="text/javascript">
var someVarInJS = '{someVarInAS}';
var someOtherVarInJS = {someOtherVarInAS};
<![CDATA[
//here be code
alert( 'this comes from flash: ' + someVarInJS + ', ' + someOtherVarInJS );
]]>
</script>;
ExternalInterface.call( "function js_" + ( new Date().getTime() ) + "(){ " + jsXML + " }" );
A few things to note:
the {} inside the javascript code will translate to the value of whatever variable you put in between
the cdata section enables you to write whatever javascript code you want, otherwise the compiler can complain.
All javascript code called through externalinterface should be placed in a named function, otherwise it will not work in a few browsers. In this code snippet I employ a little trick (new Date().getTime()) to ensure the function always has a unique name and can't conflict with another one with possibly the same name.
don't forget the ; behind </script> it tells the compiler your javascript ends there
everything javascript can do, can be done with externallinterface. i think the best way would be to port the js script to ac.
this is how you can include a tag:
ExternalInterface.call("document.getElementsByTagName('head')[0].appendChild(document.createElement('script'))");
ExternalInterface.call("document.getElementsByTagName('script')[document.getElementsByTagName('head')[0].getElementsByTagName('script').length-1].setAttribute('type', 'text/javascript')");
ExternalInterface.call("document.getElementsByTagName('script')[document.getElementsByTagName('head')[0].getElementsByTagName('script').length-1].setAttribute('src', 'http://your.server/your.js')");