AS3 function call from javascript - javascript

I am trying to call a AS3 function from javascript but getting the following error in browser:
Object doesnot support property or method myCreateFile .
Below is the AS3 class:
package {
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.net.FileReference;
import flash.events.IOErrorEvent;
import flash.events.Event;
import flash.system.Security;
public class CreateDoc extends Sprite {
private static const DEFAULT_FILE_NAME:String = "example.txt";
//FileReference Class well will use to save data
private var fr:FileReference;
public function CreateDoc()
{
// Register the function for external use.
ExternalInterface.addCallback("myCreateFile", myCreateFile);
Security.allowDomain("*");
}
public function myCreateFile():void
{
fr = new FileReference();
//open a native save file dialog, using the default file name
fr.save("Demo file", DEFAULT_FILE_NAME);
fr = null;
}
}
}
HTML code:
<html>
<head>
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
try{
var flashvars = {};
var params = {allowscriptaccess:"always", movie:"CreateDoc.swf", wmode:"opaque", menu:"false"};
var attributes = {id:"flashcontent", name:"flashcontent"};
swfobject.embedSWF("CreateDoc.swf", "flashcontent", "800", "600", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
}
catch(err){
alert(err.message);
}
</script>
<script type="text/javascript">
function doFunction(){
alert('Calling function..');
try{
var myObj = document.getElementById("flashcontent");
myObj.myCreateFile();
}
catch(err){
alert(err.message);
}
}
</script>
</head>
<body>
<div id="flashcontent">
</div>
<input id="save file" type="button" value="clickme" onclick="doFunction();" />
</body>
Any idea what is wrong when I try to call the myCreateFile() AS3 function which is present in CreateDoc class from java script?

The problem is that you have used same id in three places. Change "flashcontent" here:
swfobject.embedSWF("CreateDoc.swf", "flashcontent" , ... to something else , unique_id for example , so it will be: swfobject.embedSWF("CreateDoc.swf", "unique_id" ... . After that use this id here : document.getElementById("flashcontent"); too , like document.getElementById("unique_id");

Related

Create a Kotlin/JS WebComponent with content

I want to create a custom tag with Kotlin that contains default content. The linked example works fine, but I didn't manage to add some default content (e.g. input element) to the custom tag.
I've tried different things, but so far only managed to add the input element next to the custom tag in the DOM, but not inside it.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Client</title>
</head>
<body>
<script src="webcomponentexampleproject.js"></script>
<div id="root"></div>
</body>
</html>
client.kt
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.html.InputType
import kotlinx.html.dom.append
import kotlinx.html.dom.create
fun main() {
window.onload = {
document.getElementById("root")!!.append {
webcomponent {
text = "added it"
+"some more text"
}
}
}
}
WebComponent.kt
import kotlinx.html.*
import kotlinx.html.js.onChangeFunction
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import kotlin.properties.Delegates
#JsExport
class WebComponent(consumer: TagConsumer<*>, _text: String = "", _backgroundColor: String = "none") :
HTMLTag("webcomponent", consumer, emptyMap(), inlineTag = true, emptyTag = false), HtmlInlineTag {
var text: String by Delegates.observable(_text) { prop, old, new ->
el.value = text
}
var backgroundColor: String by Delegates.observable(_backgroundColor) { prop, old, new ->
el.style.backgroundColor = backgroundColor
}
private val el: HTMLInputElement
init {
//TODO: this input element should be INSIDE the tag
el = consumer.input {
type = InputType.text
value = this#WebComponent.text
}.unsafeCast<HTMLInputElement>()
}
}
// make the new custom tag usable via the kotlinx.html DSL
fun <T> TagConsumer<T>.webcomponent(block: WebComponent.() -> Unit = {}): T {
return WebComponent(this).visitAndFinalize(this, block)
}
Try to call onTagContentUnsafe after the element init:
private val el: HTMLInputElement
init {
el = consumer.input {
type = InputType.text
value = this#WebComponent.text
}.unsafeCast<HTMLInputElement>()
consumer.onTagContentUnsafe {
+el.outerHTML
}
}

Problem with require() function in javascript

I am trying to implement the following code in which i try to read a json file in javascript. I have two files , let one be main.html which has the main javascript code let it be called main.js , and the other is imported.js
This is the main.html file
<!Doctype html>
<html>
<head>
Dwell time for workers
</head>
<script src = https://requirejs.org/docs/release/2.3.6/r.js></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="text.json"></script>
<script src="testing_file.js"></script>
<script type = "text/javascript"></script>
<script>
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2]);
</script>
<body>
<h1> worker time : </h1>
</body>
</html>
This is the imported.js file
var that = null;
class import_file
{
constructor(title)
{
this.title = title;
that = this;
}
dwell_times()
{
console.log('osama')
var x = [5,4,3,2,1] ;
var y = x.toString();
console.log(y)
let parsed = require('./updated.json')
console.log(parsed) ;// Arham
return parsed;
}
}
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2])
I am getting the following error
Uncaught Error: Module name "updated.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (r.js:417)
at Object.localRequire [as require] (r.js:1685)
at requirejs (r.js:2046)
at import_file.dwell_times (testing_file.js:16)
at imported.js:23
What do i do to solve this error ?
Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax :
var moduleName = './updated.json';
require([moduleName], function(fooModule){
// do something
})

Import functions from another js file. Javascript

I have a question about including a file in javascript.
I have a very simple example:
--> index.html
--> models
--> course.js
--> student.js
course.js:
function Course() {
this.id = '';
this.name = '';
}
A student has a course property. like this:
import './course';
function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
}
and the index.html is like:
<html>
<head>
<script src="./models/student.js" type="text/javascript"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
window.onload= function() {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
</body>
</html>
But I am getting an error on the line "var x = new Student();":
Student is not defined
When I remove the import from Student, I don't receive the error anymore.
I have tried to use (require, import, include, create a custom function, export) and none has worked for me.
Anybody knows why? and how to fix that?
P.S. the path is correct, it comes from the autocomplete in VS Code
The following works for me in Firefox and Chrome. In Firefox it even works from file:///
models/course.js
export function Course() {
this.id = '';
this.name = '';
};
models/student.js
import { Course } from './course.js';
export function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
};
index.html
<div id="myDiv">
</div>
<script type="module">
import { Student } from './models/student.js';
window.onload = function () {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
You can try as follows:
//------ js/functions.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import completely:
//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Normally we use ./fileName.js for importing own js file/module and fileName.js is used for importing package/library module
When you will include the main.js file to your webpage you must set the type="module" attribute as follows:
<script type="module" src="js/main.js"></script>
For more details please check ES6 modules
By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import.
If you add type="module" to your <script> tag, and change the import to ./course.js (because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work.
import './course.js';
function Student() {
this.firstName = '';
this.lastName = '';
this.course = new Course();
}
<html>
<head>
<script src="./models/student.js" type="module"></script>
</head>
<body>
<div id="myDiv">
</div>
<script>
window.onload= function() {
var x = new Student();
x.course.id = 1;
document.getElementById('myDiv').innerHTML = x.course.id;
}
</script>
</body>
</html>
If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever.
You can also write a quick express server to serve your files (install Node if you don't have it):
//package.json
{
"scripts": { "start": "node server" },
"dependencies": { "express": "latest" }
}
// server/index.js
const express = require('express');
const app = express();
app.use('/', express.static('PATH_TO_YOUR_FILES_HERE');
app.listen(8000);
With those two files, run npm install, then npm start and you'll have a server running over http://localhost:8000 which should point to your files.
//In module.js add below code
export function multiply() {
return 2 * 3;
}
// Consume the module in calc.js
import { multiply } from './modules.js';
const result = multiply();
console.log(`Result: ${result}`);
// Module.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Module</title>
</head>
<body>
<script type="module" src="./calc.js"></script>
</body>
</html>
Its a design pattern same code can be found below, please use a live server to test it else you will get CORS error
https://github.com/rohan12patil/JSDesignPatterns/tree/master/Structural%20Patterns/module

Call java applet method from JavaScript = is not a function

I have defined the following Java Applet:
import java.applet.Applet;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CombineData extends Applet{
private File destinationFile;
private FileOutputStream fileOutputStream;
public boolean setUpFile(String filePath) {
// This is just to check if it is a new file we write to or not
// We could return false at once saying file already exists
boolean result;
if ((destinationFile = new File(filePath)).exists()) {
result = false;
} else {
result = true;
}
try {
fileOutputStream = new FileOutputStream(destinationFile, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return result;
}
public boolean write_line(byte[] data) {
if (fileOutputStream == null) {
return false;
} else {
try {
fileOutputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
public void finished() {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the following JavaScript
function start_button() {
combineDataApplet = document.getElementById('combineDataApplet');
combineDataApplet.setUpFile("blabl");
var filename = "~/Downloads/" + prompt("Please enter file name (remember file extenstion)", "combined_data.txt");
console.log(filename);
}
And finally the HTML
<!DOCTYPE HTML>
<html lang="en">
<head>
<script src="js/page.js"></script>
</head>
<body>
<div id="content">
<div>
<applet id="combineDataApplet" code="CombineData.class" width="350" height="350">
APPLET
</applet>
<input id="start_button" type="button" onClick="start_button()" value="start"/>
</div>
</div>
</body>
</html>
And I get the following error: TypeError: combineDataApplet.setUpFile is not a function. (In 'combineDataApplet.setUpFile("blabl")', 'combineDataApplet.setUpFile' is undefined)
I have found a few post on stackoverflow which states that I need to put it into a div block without a display:none but there are no styles on any of my divs and by such there should be no display:none.
I hope someone can help me figure out what is wrong
Programming Applets is riding a dead horse.
untested: you should access the applet this way:
document.combineDataApplet.setUpFile("blabl");
and not by document.getElementById(). The latter only gets you the DOM element containing the applet.
Edit:
here is a link from January 2016 about Oracle deprecating Applets. This article gives the further link to Oracle's whitepaper for migrating applets. I haven't read it, but it might show you some alternatives.

Returned value from python is not available at javascript

I am working on a pyqt5 application which opens up a Qwebengineview. I am also attaching a handler to the QWebchannel to communicate between javascript and python methods and setting it to the QWebengineview.
Everything is working as expected. The above code loads the HTML and the CallHandler's test() method is called from javascript. And it ran smoothly.
However, when a call from javascript is made to getScriptsPath() method, the function receives the call but returns nothing.
Below are the python and HTML codes respectively.
import os
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QUrl, QObject, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
class CallHandler(QObject):
trigger = pyqtSignal(str)
#pyqtSlot()
def test(self):
print('call received')
#QtCore.pyqtSlot(int, result=str)
def getScriptsPath(self, someNumberToTest):
file_path = os.path.dirname(os.path.abspath(__file__))
print('call received for path', file_path)
return file_path
class Window(QWidget):
"""docstring for Window"""
def __init__(self):
super(Window, self).__init__()
##channel setting
self.channel = QWebChannel()
self.handler = CallHandler(self)
self.channel.registerObject('handler', self.handler)
self.view = QWebEngineView(self)
self.view.page().setWebChannel(self.channel)
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test.html"))
local_url = QUrl.fromLocalFile(file_path)
self.view.load(local_url)
def main():
app = QApplication(sys.argv)
window = Window()
# window.showFullScreen()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
HTMLfile
<html>
<head>
</head>
<body>
<center>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script language="JavaScript">
var xyz = "HI";
window.onload = function(){
new QWebChannel(qt.webChannelTransport, function (channel) {
window.handler = channel.objects.handler;
//testing handler object by calling python method.
handler.test();
handler.trigger.connect(function(msg){
console.log(msg);
});
});
}
var getScriptsPath = function(){
file_path = handler.getScriptsPath();
//Logging the recieved value which is coming out as "undefined"
console.log(file_path);
};
</script>
<button onClick="getScriptsPath()">print path</button>
</br>
<div id="test">
<p>HI</p>
</div>
</center>
</body></html>
I am not able to decipher why handler.getScriptsPath() 's returned value is not available in javascript.
The results from your function call to getScriptsPath are returned asyncronously, so you have to pass a callback function to your handler to retrieve the result, e.g.:
handler.getScriptsPath(function(file_path) {
console.log(file_path);
});
a,b,c are parameters you pass from js to py
file_path is from py to js asynchronously
handler.getScriptsPath(a,b,c,function(file_path) {
console.log(file_path);
});

Categories