how to use js bundle in flutter android - javascript

I got a js bundle.js
<script src="./bundle.js"></script>
<script>
console.log(MyCrypto)
let SpecParams = { //初始值
cureveName: 'p256',
signHashType: 'SHA-384'
}
let MyCrypto = MyCrypto.default
let eccEnde = new MyCrypto.EccCrypto(SpecParams);
function getKeyPair() {
let keyJson = eccEnde.generateKeypair();
return keyJson
}
</script>
and there are many other functions in this bundle.js like sign、verify、encrypt、decrypt
how could I use these js function in fluter android app

Related

Use imported script inside development build of Vue

I'm currently building an application and, and I applied vue 3 only in one page via script.
<script src="https://unpkg.com/jspdf#latest/dist/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/vue#3"></script>
I'm trying to use the imported module (jsPdf) via a script, and it is not working.
methods: {
generateReport() {
let pdfName = 'test';
var doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save(pdfName + '.pdf');
}
}
This is the error when I'm trying to do the method above:
Uncaught ReferenceError: jsPDF is not defined
Is it possible to use the module imported using script in the development build of Vue? or is there any other way to generate pdf without importing scripts?
Try like following snippet
const { jsPDF } = jspdf
const app = Vue.createApp({
el: "#demo",
methods: {
generateReport() {
let pdfName = 'test';
var doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save(pdfName + '.pdf');
console.log(doc)
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/jspdf#latest/dist/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/vue#3"></script>
<div id="demo">
<button #click="generateReport">pdf</button>
</div>
Have you imported the library in the .vue file you are trying to use it in?
import { jsPDF } from "jspdf";

Trying to add a Motoko snippet to an edX page and only the HTML is being parsed

This is the current snippet that is not running any of the Motoko scripts in edX when inserted onto a page.
All that is being parsed currently is the Html part.
Are the scripts pointing to the correct file locations or have I done something wrong during the upload process?
<div id="counter" class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-motoko hljs" data-lang="motoko">actor Counter {
​
var value = 0;
​
public func inc() : async Nat {
value += 1;
return value;
};
}</code></pre>
</div>
</div>
​
​
<!-- Start of dfinity Zendesk Widget script -->
<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=53121947-c10a-484c-b99b-f89a9fb6f63e"> </script>
<!-- End of dfinity Zendesk Widget script -->
<script async type="text/javascript" src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#behavior.js"></script>
<script async type="text/javascript" src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#highlight.bundle.js"></script>
​
<script type="text/javascript" src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#run_repl.js"></script>
​
<script type="module">
import {CodeJar} from 'https://cdn.jsdelivr.net/npm/codejar#3.2.3/codejar.min.js';
import {withLineNumbers} from 'https://cdn.jsdelivr.net/npm/codejar#3.2.3/linenumbers.js';
window.CodeJar = CodeJar;
window.withLineNumbers = withLineNumbers;
</script>
<script type="module">
import {CodeJar} from 'https://medv.io/codejar/codejar.js'
</script>
<script type="text/javascript">
async function addPackage(name, repo, version, dir) {
const meta_url = `https://data.jsdelivr.com/v1/package/gh/${repo}#${version}/flat`;
const base_url = `https://cdn.jsdelivr.net/gh/${repo}#${version}`;
const response = await fetch(meta_url);
const json = await response.json()
const promises = [];
const fetchedFiles = [];
for (const f of json.files) {
if (f.name.startsWith(`/${dir}/`) && /\.mo$/.test(f.name)) {
const promise = (async () => {
const content = await (await fetch(base_url + f.name)).text();
const stripped = name + f.name.slice(dir.length + 1);
fetchedFiles.push(stripped);
Motoko.saveFile(stripped, content);
})();
promises.push(promise);
}
}
Promise.all(promises).then(() => {
Motoko.addPackage(name, name + '/');
console.log(`Loaded motoko library "${name}"`);
changeCodeBlock(); // from run_repl.js
});
}
function loadBase() {
addPackage('base', 'dfinity/motoko-base', 'dfx-0.8.4', 'src');
}
</script>
​
<script async src="https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#moc-interpreter-0.6.20.js" onload="loadBase()"></script>
after looking through your code there's a few missing pieces that may solve the problem.
The hightjs script is missing, which you can either attach to the head or body. You can choose to include their stylesheet or not.
https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/default.min.css
https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js
The run_repl here (https://courses.edx.org/asset-v1:DFINITY+IC001+3T2021a+type#asset+block#run_repl.js) has unexpected characters (backslashes) such that the file is not truly working. Please copy and replicate from here: https://github.com/dfinity/antora-sdk/blob/master/src/js/vendor/run_repl.js
There's some styling added inside Dfinity's website, which has been referenced. I've pulled it into a stylesheet on this replit project. Take a look!
https://replit.com/#Sue-AnnAnn/Motoko-highlight#index.html
There is an easier solution now!
https://embed.smartcontracts.org/motoko/g/3oBbKveNbudpGgKMb2A5wADMcv3U6CDvxfjKMvASfcmkuXEk9j7UtFCn2DpHrUVJ3dSJYEMu2bW54vZRiPhYk4MDgdXkQhHwt1HhmcLi3GpCowBeaYus4BUpMZNDMLKezqBwcMg7EXFbVvNYR5xp57dViryE9uawnFjkuZacyor5jp?lines=10
Copy the iframe code and embed it into a raw HTML page on EDX.

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

How Can I Get device Details when the user run our app?

I am New to angular js and ionic mobile apps, I am getting one error.My doubt is if the user open the app at that time i need to get mobile details like device name,version,model e.t.c..For that i wrote separate controller..
<!-- Module File -->
var moduleName = angular.module('InfoModule', ['ngRoute','ui.bootstrap','ngTouch','ngAside','ngDialog','ionic'])
.run(['$rootScope','$location','StorageService',
function ($rootScope,$location,StorageService) {
$rootScope.appInitDone = false;
$rootScope.currentPage = "home";
$rootScope.loginStatus = 0;
}]);
<!-- Controller -->
moduleName.controller('PlatformController', function ($scope,$filter,$rootScope,$apply,$location,$ionicPlatform, $cordovaDevice) {
$ionicPlatform.ready(function() {
$scope.$apply(function() {
// sometimes binding does not work! :/
// getting device infor from $cordovaDevice
var device = $cordovaDevice.getDevice();
console.log(device);
$scope.manufacturer = device.manufacturer;
$scope.model = device.model;
$scope.platform = device.platform;
$scope.uuid = device.uuid;
console.log($scope.uuid);
});
});
});
<!--This is Home Html File-->
<div ng-controller="PlatformController"></div>
<div ng-controller="HomeController">
<input type="textbox" name="searchBox" placeholder="Search Form SomeThing" class="form-control" data-ng-model="someType" ng-click="Search()" style="height:40px;margin-top:50px;"/>
</div>
<!--Injected Links -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.1.0/css/ionic.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.1.0/js/ionic.min.js"></script>
I am getting $cordovaDevice Error and $Injector Mobuler error
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.12/$injector/modulerr?p0=InfoMod…p%3A%2F%2F127.0.0.1%3A50666%2Fjs%2FScriptFiles%2Fangular.min.js%3A17%3A381)
And also where we need to call the Plat Form Controller to get device information .......Please help me.......If you have any other ideas or examples please give me the solution..please....
And Also I tried another way...In module i wrote another way...Like bellow
<!-- If tried Like this i am Getting Injector Modular like above error -->
var infomoduler = angular.module('InfoModule', ['ngRoute','ui.bootstrap','ngTouch','ngAside','ngDialog','ng-bootstrap-datepicker','angular-loading-bar','infinite-scroll','ionic'])
.run(['$rootScope','$location',
function ($rootScope,$location) {
$rootScope.appInitDone = false;
$rootScope.currentPage = "home";
$rootScope.loginStatus = 0;
ionic.Platform.ready(function(){
// will execute when device is ready, or immediately if the device is already ready.
});
var deviceInformation = ionic.Platform.device();
var isWebView = ionic.Platform.isWebView();
var isIPad = ionic.Platform.isIPad();
var isIOS = ionic.Platform.isIOS();
var isAndroid = ionic.Platform.isAndroid();
var isWindowsPhone = ionic.Platform.isWindowsPhone();
var currentPlatform = ionic.Platform.platform();
var currentPlatformVersion = ionic.Platform.version();
ionic.Platform.exitApp(); // stops the app
}]);
var infomoduler = angular.module('InfoModuler', ['ngRoute','ui.bootstrap','ngTouch','ngAside','ngDialog','ng-bootstrap-datepicker','angular-loading-bar','infinite-scroll','ionic'])
.run(['$rootScope','$location','$ionicPlatform','$apply','$cordovaDevice',
function ($rootScope,$location,$ionicPlatform,$apply,$cordovaDevice) {
$rootScope.appInitDone = false;
$rootScope.currentPage = "home";
$rootScope.loginStatus = 0;
ionicPlatFormBuddy();
function ionicPlatFormBuddy(){
$ionicPlatform.ready(function() {
$scope.$apply(function() {
// sometimes binding does not work! :/
// getting device infor from $cordovaDevice
var device = $cordovaDevice.getDevice();
debugger;
console.log(device);
$scope.manufacturer = device.manufacturer;
$scope.model = device.model;
$scope.platform = device.platform;
$scope.uuid = device.uuid;
console.log($scope.uuid);
});
});
}
}]);
Is it Correct to write the code In Module Please Give me the Solution..please..
Please add this plugin
cordova plugin add org.apache.cordova.device
Add below line of code in any of your controller file,
Controller
$ionicPlatform.ready(function() {
//find application version
if (window.cordova) {
var uuid = $cordovaDevice.getUUID();
var cordova = $cordovaDevice.getCordova();
var model = $cordovaDevice.getModel();
var platform = $cordovaDevice.getPlatform();
var platformVersion = $cordovaDevice.getVersion();
var mobileDetails = {
'uuid': uuid,
'cordova': cordova,
'model': model,
'platform': platform,
'platformVersion': platformVersion,
};
console.log('Mobile Phone details:', mobileDetails)
}
});
In order to get access to the device's details, you need to install the device plugin (org.apache.cordova.device).
navigate to your ionic/cordova project (where www lives) and type the following command.
cordova plugin add cordova-plugin-device
To get more detail about ngCordova take a look at this link
Note, you need to have ngCordova plugin added to your project. You can download it from here or via bower:
bower install ngCordova
In your code include the ngCordova script e.g.
<script src="../js/ng-cordova.js"></script>

Javascript Dojo development script error

An interesting problem about dojo toolkit and javasacript.
I am using a visual studio to developing application
I have created a module as following and named its file as calc.js
djConfig.js
var pathRegex = new RegExp(/\/[^\/]+$/);
var locationPath = location.pathname.replace(pathRegex, '');
var dojoConfig = {
async: true,
packages: [
{
name: 'application',
location: locationPath + '/js/application'
}
};
calc.js
define(["dojo/_base/declare"], function(declare) {
return declare(null, {
Sum: function(x,y) {
return x + y;
}
}); })
Once created this file I references this file in index.html file as following,
index.html
<script type="text/javascript" src="/js/application/djConfig.js"></script>
<script type="text/javascript">
require(["application/calc"],
function(calc) {
var c = new calc();
console.log(c.Sum(1, 2));
}
);
</script>
This code is wirking at first.Calculating sum and writing in concole of browser.
But than I am changing something in calc.js (ex. return x+y-1;).
The browser is giving a script error.
If I change something in index.html page - for example type a whitespace- than script is working.
All changes in calc.js file is throwing script error, if I do not change somewhere in index.html
Even If I type a whitespace or add a line in index page, every thing is working.
Did you encounter a problem like this?

Categories