reading flashvars problem for swfobject - javascript

I have a flash swf of 1.2mb.
am embeding it with swfobject using dynamic embeding .
<script type="text/javascript">
var flashvars = {};
flashvars.campaignid = "12345678890";
var params = {};
params.allowscriptaccess = "always";
var attributes = {};
swfobject.embedSWF("soccer.swf", "myAlternativeContent", "550", "400", "10.0.0", false, flashvars, params, attributes);
</script>
am tring to read campaignid inside my document class ...
the code is like
public function Main()
{
loaderInfo.addEventListener(ProgressEvent.PROGRESS,update);
loaderInfo.addEventListener(Event.COMPLETE,onLoadedMovie);
}
private function update(e:ProgressEvent):void
{
}
private function onLoadedMovie(e:Event)
{
campId=this.root.loaderInfo.parameters["campaignid"];
}
when i alert the value i got null
when i use the same method in a small file it works..
can anyone help me?
regards

I got the answer by adding variable in the embed code. like this
swfobject.embedSWF("soccer.swf?campaignid=1234556"", "myAlternativeContent", "550", "400", "10.0.0", false, flashvars, params, attributes);
Thanks for the help :)

Adam Harte's answer is correct, I think the problem lies somewhere within your AS3 code, the following especially confused me:
public function Main()
{
loaderInfo.addEventListener(ProgressEvent.PROGRESS,update);
loaderInfo.addEventListener(Event.COMPLETE,onLoadedMovie);
}
private function update(e:ProgressEvent):void { }
private function onLoadedMovie(e:Event)
{
campId=this.root.loaderInfo.parameters["campaignid"];
}
I've created a simple(and working) example of how your code should look:
index.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FlashVars</title>
<meta name="language" content="en" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<script src="js/swfobject.js" type="text/javascript"></script>
<script type="text/javascript">
var flashvars = { campaignid: "12345678890" };
var params = { menu: "false", scale: "noScale", allowFullscreen: "true", allowScriptAccess: "always", bgcolor: "", wmode: "direct" };
var attributes = { id:"FlashVars" };
swfobject.embedSWF("FlashVars.swf", "altContent", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
</script>
<style type="text/css">
html, body { height:100%; overflow:hidden; }
body { margin:0; }
</style>
</head>
<body>
<div id="altContent">
<h1>FlashVars</h1>
<p>Alternative content</p>
<p>
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
</p>
</div>
</body>
</html>
Main.as(document class):
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
if (loaderInfo.parameters.campaignid)
{
var textField:TextField = new TextField();
textField.autoSize = TextFieldAutoSize.LEFT;
textField.text = loaderInfo.parameters.campaignid;
addChild(textField);
}// end if
}// end function
}// end class
}// end package
The following is an image of the example beening run in a browser:

Maybe try getting the var after your Main class has been added to the stage. This will make sure everything is loaded and ready. Try something like this:
public function Main()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var campId:String = this.root.loaderInfo.parameters["campaignid"];
trace('campId', campId);
}

Related

How can I communicate between an IFrameElement and Dart using JavaScript?

I'm a noob to Flutter Web. I have a package that I'm trying to create support for in Flutter Web, but it uses a webview for some functions. Webviews aren't supported in Flutter Web so I'm using a IFrameElement and ui.platformViewRegistry.registerViewFactory() to act like a webview. I'm passing an HTML String to be loaded rather than a file.
I need to be able to run JS functions and get data from JS. I've tried a lot of different things with events and event listeners, also context.callMethod() and none of it has worked so far. Is there a simple way to accomplish this?
For reference, I am using the Summernote library and I can run something like \$('#summernote').summernote('reset'); to reset the Summernote editor. Sometimes I need to get data from JS so I am running var str = \$('#summernote').summernote('code'); console.log(str); which gives me the HTML code in the editor.
Thanks in advance!
Code for reference:
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:html_editor_enhanced/html_editor.dart';
import 'package:html_editor_enhanced/utils/pick_image.dart';
import 'package:path/path.dart' as p;
import 'package:flutter/material.dart';
import 'dart:html' as html;
import 'dart:js' as js;
import 'dart:ui' as ui;
bool callbacksInitialized = false;
js.JsObject jsDocument;
class HtmlEditorWidgetWeb extends StatelessWidget {
HtmlEditorWidgetWeb({
Key key,
this.value,
this.height,
this.useBottomSheet,
this.imageWidth,
this.showBottomToolbar,
this.hint,
this.callbacks,
this.toolbar,
this.darkMode
}) : super(key: key);
final String value;
final double height;
final bool useBottomSheet;
final double imageWidth;
final bool showBottomToolbar;
final String hint;
final UniqueKey webViewKey = UniqueKey();
final Callbacks callbacks;
final List<Toolbar> toolbar;
final bool darkMode;
final String createdViewId = 'html_editor_web';
#override
Widget build(BuildContext context) {
String summernoteToolbar = "[\n";
for (Toolbar t in toolbar) {
summernoteToolbar = summernoteToolbar +
"['${t.getGroupName()}', ${t.getButtons()}],\n";
}
summernoteToolbar = summernoteToolbar + "],";
String darkCSS = "";
if ((Theme.of(context).brightness == Brightness.dark || darkMode == true) && darkMode != false) {
darkCSS = "<link href=\"packages/html_editor_enhanced/assets/summernote-lite-dark.css\" rel=\"stylesheet\">";
}
String htmlString = """
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="description" content="Flutter Summernote HTML Editor">
<meta name="author" content="xrb21">
<title>Summernote Text Editor HTML</title>
<script src="main.dart.js" type="application/javascript"></script>
<script src="app.js" defer></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote-lite.min.js"></script>
$darkCSS
<script>
function test() {
console.log("Listening");
}
</script>
</head>
<body>
<div id="summernote-2"></div>
<script type="text/javascript">
\$('#summernote-2').summernote({
placeholder: "$hint",
tabsize: 2,
height: ${height - 125},
maxHeight: ${height - 125},
toolbar: $summernoteToolbar
disableGrammar: false,
spellCheck: false
});
document.addEventListener("setFS", function(){
console.log('fired');
\$('#summernote-2').summernote("fullscreen.toggle");
});
</script>
<style>
body {
display: block;
margin: 0px;
}
.note-editor.note-airframe, .note-editor.note-frame {
border: 0px solid #a9a9a9;
}
.note-frame {
border-radius: 0px;
}
</style>
</body>
</html>
""";
html.window.onMessage.forEach((element) {
print('Event Received in callback: ${element.data}');
});
// todo use postmessage and concatenation to accomplish callbacks
final html.IFrameElement iframe = html.IFrameElement()
..width = MediaQuery.of(context).size.width.toString() //'800'
..height = MediaQuery.of(context).size.height.toString() //'400'
..srcdoc = htmlString
..style.border = 'none'
..onLoad.listen((event) async {
html.document.on['setFS'].listen((html.Event event) {
print("HEY! I'M LISTENING!");
});
html.document.dispatchEvent(html.Event("setFS"));
});
ui.platformViewRegistry.registerViewFactory(
createdViewId, (int viewId) => iframe);
return Column(
children: <Widget>[
Expanded(
child: Directionality(
textDirection: TextDirection.ltr,
child: HtmlElementView(
viewType: createdViewId,
)
)
),
],
);
}
}
A little bit hacky, but here's the solution I use:
Dart -> JS
In dart:
html.window.postMessage(//data to send here, "*");
and in the IframeElement HTML <script>:
window.parent.addEventListener('message', handleMessage, false);
function handleMessage(e) {
var data = e.data;
}
I personally use JSON when sending data to make it easier to send/receive/parse. So in Dart that is a Map<String, dynamic>, sent like this:
final data = Map<String, dynamic>{
//your data here
}
final jsonEncoder = JsonEncoder();
final json = jsonEncoder.convert(data);
html.window.postMessage(json, "*");
and in JS:
window.parent.addEventListener('message', handleMessage, false);
function handleMessage(e) {
var data = JSON.parse(e.data);
}
A suggestion would be to create a unique key/string that you can pass in between JS and Dart so you make sure you are intercepting the correct postMessage every time.
JS -> Dart
In the IframeElement HTML <script>:
window.parent.postMessage(//data to send, "*");
and in Dart:
html.window.onMessage.listen((event) {
var data = event.data;
});
Again, I use JSON to communicate because I think it makes things easier. Use JSON.stringify() in JS and json.decode() in Dart.

Function is not define

Here is my code :
// And my javascript file verbatims.js :
class Verbatims {
list() {
return ["c'est super", "j'aime pas", "ça marche bien"];
}
}
module.exports = Verbatims;
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta content="X-Content-Type-Options: nosniff">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script>
<script src="/src/verbatims.js" type="application/javascript"></script>
<title>My Project</title>
</head>
<body>
<div id="PRISME_data">
Le nombre de requête est de : {{ nb_request }}<br>
<button v-on:click="change">Change value</button>
<button v-on:click="stop">Arrêter</button>
</div>
<script>
let app = new Vue({
el:'#PRISME_data',
data: {
nb_request: "toto",
ite: 0
},
methods: {
change: function() {
changeNbRequest()
},
stop: function() {
clearInterval()
}
}
});
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
</body>
</html>
When I try to display my page with my node server I have this error :
Uncaught ReferenceError: Verbatims is not defined at index:45
on this line : let verbatim = new Verbatims().list()[ite];
I don't see why, I have try a lot of things but nothing work ! Do you have any idea ?
Thank you :)
This might be happening because of the following:
The verbatims.js file is not loading in the browser because of
wrong path.
The verbatims.js file that reached the browser does
not contain your class.
You did not import the Verbatims class on the referencing script.
Fix for 3rd option should be like this:
<script type="module">
import {Verbatims} from './src/vebatim.js';
....ommitted for brevity
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
Additional TIP
To improve your code, try to place all the JS code inside your index.html to an external file so you can take advantage of ES6 import/export features.

How to call a method in a different java class inside javascript

I'm having an application which takes input from a popup dialog.When a user enters a text in the text field of a popup dialog.I need to pass that text to another method ina different class.How can I achieve this. My code is shown below.
viewRoles.jsp
<%#page contentType="text/html" import="com.model.Data" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="bootstrap.css" type="text/css" rel="stylesheet">
<script>
window.onload=function()
{
var el=document.getElementById('btnAddNewRole');
el.onclick=function()
{
var my_text=prompt('Enter text here');
if(my_text){
$.ajax({
url: '/com.model/Data/addRole('+my_text+')',
success: function(my_text){
alert("Inserted")
}, error: function(){
// when got error
}
});
}
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>View Roles</title>
</head>
<body><br><br>
<button id="btnAddNewRole" class="btn btn-info">Add New Role</button>
</body>
</html>
Data.java in com.model package
package com.model;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.hibernate.Session;
#ManagedBean
#SessionScoped
public class Data {
private Roles r;
private HibernateUtil helper;
private Session session;
public void addRole(String roleTitle){
r=new Roles(roleTitle);
session = helper.getSessionFactory().openSession();
session.beginTransaction();
session.save(r);
session.getTransaction().commit();
session.close();
}

How can we use addCallback function in flex

How can i call the flex frunction from the java script?
i am using below code which is define in below links
ExternalInterface.addCallback( "javascriptfunction", flexfunction);
http://www.switchonthecode.com/tutorials/flex-javascript-basics-using-externalinterface
http://circlecube.com/2010/12/actionscript-as3-javascript-call-flash-to-and-from-javascript/
You should give more context for your problem. From what I read on the tutorials, it is possible that you have omitted to add security access to your code. More precisely look here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html#addCallback%28%29 , especially here:
SecurityError — The containing environment belongs to a security sandbox to which the calling code does not have access. To fix this problem, follow these steps:
In the object tag for the SWF file in the containing HTML page, set the following parameter:
param name="allowScriptAccess" value="always"
In the SWF file, add the following ActionScript:
flash.system.Security.allowDomain(sourceDomain)
Hope it helps.
In flex 4.5
Add a addcallback first, like this in your mxml
public function initApp():void {
ExternalInterface.addCallback("myFlexFunction",myFunc);
}
myFlexFunction can now be accessed from your javascript.
Make your index.template.html looks like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>addCallback() Wrapper</title>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
var swfVersionStr = "0";
var xiSwfUrlStr = "";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
var attributes = {};
attributes.id = "AddCallbackExample";
attributes.name = "AddCallbackExample";
attributes.align = "middle";
swfobject.embedSWF(
"AddCallbackExample.swf", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
</script>
</head>
<SCRIPT LANGUAGE="JavaScript">
function callApp() {
window.document.title = document.getElementById("newTitle").value;
var AddCallbackExample = document.getElementById("AddCallbackExample");
AddCallbackExample.myFlexFunction(window.document.title);
}
</SCRIPT>
<body>
<form id="f1">
Enter a new title: <input type="text" size="30" id="newTitle" onchange="callApp()">
</form>
<div id="flashContent"/>
</body>
</html>
and your flex application like this
<?xml version="1.0"?>
<!-- wrapper/AddCallbackExample.mxml -->
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="initApp()">
<fx:Script>
import flash.external.*;
public function initApp():void {
ExternalInterface.addCallback("myFlexFunction",myFunc);
}
public function myFunc(s:String):void {
l1.text = s;
}
</fx:Script>
<s:Label id="l1"/>
</s:Application>
Hope this helps

Flex/AIR calling Javascript functions

I have problem with calling javascript function from my AIR / Flex App. In web App this is easy with externallInterface, but in native app it is a problem. My AIR app is similar like this ....
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="init()" ... >
<mx:Script>
<![CDATA[
private function init():void
{
myHTML.addEventListener(Event.HTML_DOM_INITIALIZE,DOMInit);
myHTML.location="myAIRHTML.html";
}
private function DOMInit(e:Event):void{
myHTML.htmlLoader.window.inputFunction = testInputFunction;
}
private function testInputFunction(so:String):void{
//some code ......
}
public function someFunction(e:AIREvent):void{
myHTML.htmlLoader.window.outputFunction(e.param);
}
_]]>
</mx:Script>
<mx:HTML id="myHTML" width="5" height="5" visible="true" />
</mx:WindowedApplication>
myAIRHTML.html is
<html>
<head>
<script language="Javascript">
var interface = {};
function outputFunction(param){
var childInterface = document.getElementById("mySandbox").childSandboxBridge;
childInterface.remoteFunction(param);
}
interface.inputFunction = function(someData){
testInputFunction(someData);
}
function initBridge(){
document.getElementById("mySandbox").parentSandboxBridge = interface;
}
</script>
</head>
<body>
<iframe id="mySandbox"
src="js.html"
sandboxRoot="http://remote.example.com/js/"
documentRoot="app:/myAIRSandbox/"
ondominitialize="initBridge()">
</iframe>
</body>
</html>
and js.html is
<html>
<head>
<script language="Javascript" src="http://www/otherexample.com/other.js"></script>
<script language="Javascript" >
var interface = {};
interface.remoteFunction = function(st){
alert("st");
callFunctionInOtherJS(st);
}
window.childSandboxBridge = interface;
var someObject = {};
someObject.SomeFunction = function(someParam){
window.parentSandboxBridge.inputFunction(someParam);
}
</script>
</head>
<body ></body>
</html>
This throw "TypeError: Undefined value" when I call "remoteFunction" in myAIRHTML.html. It something important what I missed? Can anyone help? It something important what I forget about documentRoot - I don't use this name on other place ..... Thanks for all replies
it seems a bit confused to me anyway if i've understand this is your error:
If you define this
myHTML.htmlLoader.window.inputFunction = testInputFunction;
You js in myAIRHTML.html can't call testInputFunction(someData); but inputFunction(someData) because you passed your AS3 function testInputFunction to a variable called inputFunction
Hope this helps

Categories

Resources