calling javascript from Dart - javascript

i was able to fire off an alert message from dart, but couldn't figure out how to call a function I wrote in another js file from dart. This would have been a great selling point if it was straight forward. I did see this post, which got me started, but i feel there must be a way, so please share the love if you figured it out.
Here's what I've done:
Add this to yaml file:
dependencies:
js:
hosted: js
Add import statement to top of dart file: import 'package:js/js.dart' as js;
Add this bit of code to show alert message
js.scoped(() {
js.context.alert("jump for joy!");
});
Here's the part which I think should work but doesn't: given that I have a javascript function doSomething(), I should be able to call
js.context.doSomething();

First add the js package as dependency in your pubspec.yaml :
dependencies:
js: any
Then you can use your own js function myFunc() like that :
import 'package:js/js.dart' as js;
main() {
js.context.myFunc();
}
js.context is an alias to javascript window.
See Using JavaScript from Dart: The js Library for more details.

Maybe my answer will be worth it for somebody, so that's why I'm posting a simple JS function call from Dart.
Add the js package dependency:
dependencies:
js: any
Create a JS file, let's say example.js:
function test() {
return 12+20;
}
Add the example.js above inside index.html with the <script src="..."> tag.
Interop the function above from JS to Dart:
#JS()
library t;
import 'package:js/js.dart';
#JS()
external int Test();
class MyOwn {
int get value => Test();
}
And, in AngularDart's TODOLIST — which is default component available —:
#override
Future<Null> ngOnInit() async => print(MyOwn().value);

Related

Run some Javascript file like index.js in Flutter Webview

how I can run Javascript file in the flutter_webview_plugin. I try it with this.
flutterWebViewPlugin.evalJavascript("require('./index.js');");
But nothing happens.
when I try to run flutter code it's shows nothing
my index.Js file contains a simple alert statement
alert('hello world');
First, You used "require" function. this function is not implemented in javascript itself. it's a part of NodeJs. so that function will not work.
In order to load a js file into flutter, you should consider it as a text file and load it properly. So, you need to add the file to assets folder, add into pubspec file, then load it. read the full answer here
Second, you used evalJavascript. this function can be used in many different situations. but it will work only if you have a view panel.
Check below example:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
main() async {
String jsCode = await rootBundle.loadString('assets/javascript.js');
runApp(new MaterialApp(
home: LunchWebView(jsCode),
));
}
class LunchWebView extends StatelessWidget {
final String text;
LunchWebView(this.text);
#override
Widget build(BuildContext context) {
final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
flutterWebviewPlugin.launch('https://www.google.com');
flutterWebviewPlugin.evalJavascript(text);
return Container();
}
}
NOTE: : I didn't handle reloading and other exceptions. you should check if there is any webview object open and then call Lunch method.

Unable to use good old JS function with some jQuery in Laravel 5.7 blade template with webpack - method not found

I'm using Laravel 5 Boilerplate that comes with some structure already done.
I want to call a simple JavaScript method from the blade. Here's what I did:
1) Created file called test123.js
content of test123.js:
function test123() {
$(document).ready(function () {
console.log('hello from test123');
});
}
2) I opened the existing app.js and added:
import './test123';
3) I called npm dev run - all green, all OK.
4) In blade index.blade.php I typed:
#push('after-scripts')
<script>
test123();
</script>
#endpush
I went to compiled file:
<script src="http://foo.local/js/backend.js?id=8dbe74e012c3122422da"></script>
My method is there:
however it's not visible.
I guess it's about scopes? I don't want to make it window.test123. Should I? I just want define good old JS / jQuery method and invoke it only when needed in specific templates.
"Modern" JS is not my strong point as I find it very convoluted. I haven't touched default webpack.mix.js.
mix.setPublicPath('public');
mix.sass('resources/sass/frontend/app.scss', 'css/frontend.css')
.sass('resources/sass/backend/app.scss', 'css/backend.css')
.js('resources/js/frontend/app.js', 'js/frontend.js')
.js([
'resources/js/backend/before.js',
'resources/js/backend/app.js',
'resources/js/backend/after.js'
], 'js/backend.js')
.extract([
'jquery',
'bootstrap',
'popper.js/dist/umd/popper',
'axios',
'sweetalert2',
'lodash',
'#fortawesome/fontawesome-svg-core',
'#fortawesome/free-brands-svg-icons',
'#fortawesome/free-regular-svg-icons',
'#fortawesome/free-solid-svg-icons'
]);
Please help me to achieve this simple thing. I know the solution probably is not difficult but I don't know what to do…
Thank you.
Edit 1: I almost forgot. Here's the Boilerplate structure:
Edit 2: User brk requested some more screenshots:
Try exporting the function explicitly:
export function test123() {...}
and later import it:
import 'test123' from './test123';
You can try do this with require.js
//declare fn test123
test123(){ ...do something}
module.exports.test123 = test123;
and then
let test123 = require('./test123');
Here you can find more information about using require.js in browser with jquery https://requirejs.org/docs/jquery.html

How to use methods from external js in Angular

I need to call a function from external js file into my Angular component
I already go through the related question
How can i import external js file in Angular 5?
How to include external js file in Angular 4 and call function from angular to js
My External JS (external.js)
var radius = 25;
function calculateRadius(pi) {
let piValue = 3.14159;
if(pi) {
piValue = pi;
}
var result = piValue * radius * radius;
console.log('Result: ', result);
}
function wrapperMethod(pi) {
console.log('Hi, this is from wrapper method');
calculateRadius(pi)
}
I added the said JS file in the angular.json under scripts block
"scripts": [
"src/assets/external.js",
]
In the CircleComponent, I would like to call the method
import wrapperMethod from '../../src/assets/external.js';
#Component({
selector: 'app-circle',
templateUrl: './circle.component.html',
styleUrls: ['./circle.component.css']
})
export class CircleComponent implements OnInit {
constructor() { }
ngOnInit() {
wrapperMethod(3.14159);
}
}
But its failing to call the method. Kindly assist me how to achieve this.
Note: The said methods as just an example methods, I want to implement this logic with the complex code file. The said question tells about typings.d.ts, but I don't know where is typings.d.ts in my Angular project. Kindly brief me regarding this. If the said question gives good solution means, why should I post this question.
Angular Structure (Created using Angular CLI)
I don't know where is typings.d.ts, could anyone please tell me where is typings.d.ts - which is mentioned in the said questions How to include external js file in Angular 4 and call function from angular to js
You can follow this below steps
1) First add a reference of your external JS file for importing it to the component.
import * as wrapperMethods from '../../src/assets/external.js';
2) Now declare a "var" of the same name that your function has inside external JS.
declare var wrapperMethods: any;
3) ngOninit(){
wrapperMethods();
}
put your external .js file under scripts in build
if still can not see methods inside it put in in index.html
<script src="assets/PATH_TO_YOUR_JS_FILE"></script>
in your component after import section
declare var FUNCTION_NAME: any;
ANY_FUNCTION() {
FUNCTION_NAME(params);
}
Don't get confused with typings.d.ts. Follow below steps.
1.Add your external file inside assets folder. The content of this file will be by default included as per your angular-cli.json.
2.The function of your js which you're going to use must be exported. i.e.
export function hello() {
console.log('hi');
}
3.Import your file inside your component as below.
import * as ext from '../assets/some-external.js';
4.Now you can reference it like
ext.hello();
Steps:-
1. create a external js file.
2. In component.ts use the below code.
ngOnInit() {
this.loadJsFile(JsFilePath);
}
public loadJsFile(url) {
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
3. If u use jquery then define selector in html to render. Or store data in variable.
Make sure you have to add jquery cdn in index.html and you have to install Jquery and its types package from npm.

How does the JavaScript Import work under the hood?

How does the import statement actually work in JavaScript? I read the documentation and it says that it places exported code within the scope of the file. Does that mean that the code is copied over into the file where I type import?
For example - in library.js I have:
export {export function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
In main.js I have:
import { getUsefulContents} from 'library.js';
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });
This allows me to call getUsefulContents() in main.js. My question is, does main.js now have the contents that I exported from library.js?
Is using import the same as just having physically defined getUsefulContents() in main.js?
function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });
The main reason why I ask is because I want to know if using import will have an effect on main.js file size? Or is something else going on under the hood?
Thank you!
Depends on how you are using main.js. If you run it through a bundler, then the bundler will probably include library.js into main.js to pack it up into one file. In that case, the only advantage would be maintainability and ease of development because you are focused on the file you are working on. If you are simply running the import statement and deploying your application, the import statement won't affect the file size of main.js.
It just namespacing it within the file that you are importing it to so
any code from useful-library.js is included in the file, I visualize it this way
import { usefulCodeFromLibrary } from './useful-library.js';
((usefulCodeFromLibrary)=>{
// My excellent code
// Imported code doing it's job
usefulCodeFromLibrary.someHelperFunction()
}()

Consuming JavaScript code in TypeScript application

I'm learning TypeScript and as a practice I wanted to try to consume JavaScript code in my TS app.
For example, this is your .js file:
foo = function() {
console.log("imported from Test.js");
};
I have managed to make it work with the following code:
//Test.js
module.exports.foo = function() {
console.log("imported from Test.js");
};
//Test.d.ts
declare module 'Test' {
export function foo(): void;
}
//HelloWorld.ts
import * as t from './Test';
t.foo();
This code executes fine but produces the following error which I cannot get rid of:
Error:(1, 20) TS2306:File 'C:/Users/2512/Projects/TypeScript/Test.d.ts' is not a module.
Also, if module.exports is used in Test.js then foo() cannot be called in Test.js as foo(); as it produces a foo is not defined error.
My main question is, what is the most up-to-date practice to import .js code into .ts without making any modification to an existing .js file?
I've spent many hours looking for the answer but could not find an ideal solution. Thank you.
P.S. I have typings installed in the project so I believe /// <reference path="Test.d.ts" /> is not required in Test.ts.

Categories

Resources