Cannot load modules with traceur - tries to access file via xhr - javascript

I am trying to use traceur. When I want to load a module though, I get an error that it was unsuccessful. My code is based on the example traceur provided in its documentation on modules.
Here is the main.html:
<script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
<script src="https://google.github.io/traceur-compiler/src/bootstrap.js"></script>
<script>
System.traceurOptions = { experimental: true }
</script>
<script type="module" src="ProfileView.js"></script>
And the loaded module:
// ProfileView.js
import {firstName, lastName, year} from './Profile.js';
function setHeader(element) {
element.textContent = firstName + ' ' + lastName;
}
// rest of module
// Profile.js
export var firstName = 'David';
export var lastName = 'Belle';
export var year = 1973;
I get the following error in Chrome:
XMLHttpRequest cannot load
file:///C:/Code/Tests/Traceur/ProfileView.js. Cross origin requests
are only supported for protocol schemes: http, data, chrome,
chrome-extension, https, chrome-extension-resource.
WebPageTranscoder FAILED to load
file:///C:/Code/Tests/Traceur/ProfileView.js
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest':
Failed to load 'file:///C:/Code/Tests/Traceur/ProfileView.js'.
I know that you cant make xhr-requests via the file system but I have seen some tutorials in which the code is structured similarly to mine and it works there...
What may I be doing wrong?

You cannot access the file system with xhr, you should open those pages over http by running a local webserver. If you really want to enable file system access you can: http://www.chrome-allow-file-access-from-file.com/
I.e. you start chrome chrome.exe --allow-file-access-from-files

Related

How to use CryptoJs in the Javascript

I installed crypto-js like so in my Blazor project
PM> npm install crypto-js
then in the index.html, I used it like so
<script>
... OTHER FUNCTIONS
function encryptMessage(message, key) {
const keyOffSet = 10;
const data = CryptoJS.enc.Utf8.parse(message);
const keyLength = 24
}
</script>
How come that I get an error of
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: CryptoJS is not defined
ReferenceError: CryptoJS is not defined
You need to import CryptoJS by adding CryptoJS CDN. Add the following code before your script tag which contains the logic.
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js" integrity="sha512-E8QSvWZ0eCLGk4km3hxSsNmGWbLtSCSUcewDQPQWZF6pEU8GlT8a5fF32wOl1i8ftdMhssTrF/OhyGWwonTcXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Note: If you still get error, check details of the GET request performed in Dev Tool's Network tab, it would probably have to do with CORS or some other network policy.

How to load .wasm file in React-Native?

I have been trying to load a WebAssembly (.wasm) file - generated C++ code compiled to WebAssembly by Emscripten - in a React-Native app.
This is my code to fetch the .wasm file:
import fs from 'react-native-fs';
if (!global.WebAssembly) {
global.WebAssembly = require('webassemblyjs');
}
const fetchWasm = async () => {
const wasm = await fetch(`${fs.MainBundlePath}/calculator.wasm`);
console.log(wasm);
// Returns: Response {type: "default", status: 200, ok: true, statusText: undefined, headers: Headers, …}
const mod = await WebAssembly.instantiateStreaming(wasm);
console.log(mod);
// Throws: TypeError: Failed to execute 'compile' on 'WebAssembly': An argument must be provided, which must be a Response or Promise<Response> object
};
I tried everything in the Google search results I could find, but nothing worked so far. Unfortunately, the most related questions were unanswered.
Is there anyone who knows what I am doing wrong? Any help would be greatly appreciated!
There is one thing to be aware when wanting to load wasm :
Your webserver must report .wasm mime type as "application/wasm" , otherwise you won't be able loading it.
I assume still React-native JS runtime JSC still not support WebAssembly in Android build
the issue is still open
https://github.com/react-native-community/jsc-android-buildscripts/issues/113
Another way is to use Webview but I assume it is not you are expecting.
https://github.com/ExodusMovement/react-native-wasm

Access to script blocked by CORS policy

I am making a simple test project including 2 JavaScript files , where i export and import modules , as shown below .
However ,when opening html page , an error generated in the console shows that :
Access to script at 'file:///C:/Users/index2.js' from origin 'null' has been blocked by CORS policy
Failed to load resource: net::ERR_FAILED (index2.js:1)
I tried to desactivate CORS but that leads always to the same error , i am using Google Chrome browser .
what is abnormal in code and what to do to resolve this problem ?
index2.js :
export default class test {
static method () {
return ('hello world' ) ;
}
index.js :
import test from './index2.js';
console.log (test.method()) ;
in index.html :
<script type = "module" src="./index.js"></script>
I resolved the problem by setting up a local webserver , I Used XAMPP , the link below shows the installation and usage :
https://www.maketecheasier.com/setup-local-web-server-all-platforms/

Working with JavaScript module

I read this and this, and wrote the below files:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="module">
(async () => {
const moduleSpecifier = './lib.mjs';
const {_default, repeat, shout} = await import(moduleSpecifier);
repeat('hello');
// → 'hello hello'
document.getElementById("demo").innerHTML = shout('Dynamic import in action');
// → 'DYNAMIC IMPORT IN ACTION!'
})();
</script>
</head>
<body>
<h1>This is a Heading</h1>
<p id="demo">Loading ..</p>
</body>
</html>
lib.mjs:
export const repeat = (string) => `${string} ${string}`;
export function shout(string) {
return `${string.toUpperCase()}!`;
}
But once trying it at chrome, I got the below:
Access to Script at 'file:///Users/hasan/Documents/mjs/lib.mjs' from
origin 'null' has been blocked by CORS policy: Invalid response.
Origin 'null' is therefore not allowed access.
In nodejs I can add the below line, but can I do it to my file, knowing that it is not running from server!
response.setHeader('Access-Control-Allow-Origin', '*');
UPDATE
I tried running it from this server, and set the CORS, but got the below error:
Failed to load module script: The server responded with a
non-JavaScript MIME type of "". Strict MIME type checking is enforced
for module scripts per HTML spec.
UPDATE 2
It worked with me when I renamed the .mjs to .js, is this means the .mjs not yet supported!!
The first error output is because JavaScript modules are fetched with CORS, and I guess you did not use a server that set up the proper headers as explained in this article: https://developers.google.com/web/fundamentals/primers/modules
In your second attempt with 200 OK Web Server extension for Chrome, it does not yet support JavaScript modules because of lacking MIME type support. There are an issue for this on the developers' Github https://github.com/kzahel/web-server-chrome/issues/133

Chrome can't load web worker

I am working on a project that uses a web worker.
In my head section I have this code:
var worker = new Worker("worker.js");
// More code
This works fine in Safari, but Chrome reports the following error:
Uncaught SecurityError: Failed to create a worker: script at '(path)/worker.js' cannot be accessed from origin 'null'.
Why does this work perfectly in Safari but not Chrome? How do I fix this?
Thank you.
Chrome doesn't let you load web workers when running scripts from a local file.
I use a workaround. Chrome blocks Worker but not <script>. Hence the best way to make a universal solution is this:
function worker_function() {
// all code here
}
// This is in case of normal worker start
// "window" is not defined in web worker
// so if you load this file directly using `new Worker`
// the worker code will still execute properly
if(window!=self)
worker_function();
You then link it as normal <script src="...". And once the function is defined, you use this abomination of a code:
new Worker(URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], {type: 'text/javascript'})));
The problem has been properly explained by Noble Chicken but I have a more general solution for it. Instead of installing wamp or xamp, with python you can navigate to the folder your project is hosted in and type: python -m http.server
Just that and you will have a running server on that folder, reachable from localhost.
You can also use the --allow-file-access-from-files flag when you launch Chrome.
Example for MacOsX :
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files
More info : Web worker settings for chrome
It is because of the security restrictions. You need to use http:// or https:// protocol instead of file:///.
If you have NodeJS installed, you can simply do the following.
- Note that this is one of many options available
Install local-web-server
$ npm install -g local-web-server
Now you can use it in any folder that you want to access the contents through http .
$ ws
Navigate to http://localhost:8000 (default port: 8000)
I had the same problem as your post too. The solution is that you have to run it with localhost (wamp or xamp). It will done.
Another workaround is use Google's web server for Chrome extension. Choose your work directory and start the server, Done!
This is inspired by Thomas answer above. But with one caveat that
I wanted to distribute only the HTML, so i manually converted the js to dataURL. and enabling the data URL check box in it.
const myWorker = new Worker("data:application/x-javascript;base64,b25tZXNzYW...");
Easy way to make local http server in chrome is this app:
Web Server for Chrome
https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb/related
Description:
A Web Server for Chrome, serves web pages from a local folder over the network, using HTTP. Runs offline.
Web Server for Chrome is an open source (MIT) HTTP server for Chrome.
It runs anywhere that you have Chrome installed, so you can take it anywhere. It even works on ARM chromebooks.
It now has the option to listen on the local network, so other computers can access your files. Additionally, it can try and get an internet address.
Many people use this to do basic web development on a chromebook. It is also handy for sharing files over a local network between computers, or even on the internet.
Once you install it, navigate to http://127.0.0.1:8887
And it is not unsecure as flag --allow-file-access-from-files
you need a web server for request from HTTP protocol Instead of local file
and work correctly :)
Chrome load the file but cannot run it. Use Firefox. It's working for me.
With Python 2.x being more widely deployed than Python 3.x, something like python -m SimpleHTTPServer 8000 is more generally applicable, and not just for Mac OS X. I found it necessary for use under Cygwin, for instance.
With that in place, this example worked like a champ.
function worker_fun(num){
num ++
// console.log(num)
postMessage(num);
setTimeout(worker_fun.bind(null,num), 500)
}
var w
function startWorker(){
var blob = new Blob([
"onmessage = function(e){\
" + worker_fun.toString() + "\
worker_fun(e.data.num);}"
]);
var blobURL = window.URL.createObjectURL(blob);
if (typeof(Worker) != 'undefined'){
if (typeof(w) == 'undefined'){
w = new Worker(blobURL);
w.onmessage = function(event){
document.getElementById('num').innerHTML = event.data;
}
w.postMessage({
num:parseInt(document.getElementById('num').innerHTML)})
}
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
As mentioned chrome does not support it. I like to define my workers in the same file. This is a working workaround which will increase a number found in innerHTML of the element the with id=num every 500ms.
A probably reason is chrome doesn't let you load web workers when running scripts from a local file. And I try run the code on my firefox, can not either.
To load web worker from file in a project set up with Webpack and TypeScript I used a script as Tomáš Zato suggested. However, I had to modify the worker file.
worker.ts
(() => {
console.log("worker_function loaded");
// #ts-ignore
window.worker_function = () => {
self.onmessage = ({ data: { question } }) => {
// #ts-ignore
self.postMessage({
answer: 42,
});
};
}
})();
index.ts
async function run() {
console.log('run()');
const worker = new Worker(
// #ts-ignore
URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], { type: 'text/javascript' }))
);
worker.postMessage({
question: 'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
});
worker.onmessage = ({ data: { answer } }) => {
console.log(answer);
};
}
run();
index.html
<html lang="en-us">
<head>
<meta charset="utf-8" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Offscreen canvas with web worker sample project</title>
<script async type="text/javascript" src="worker.js"></script>
<script async type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>web worker sample project</h1>
</body>
</html>
webpack.config.js (version 5)
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
mode: "production",
entry: {
app: "./src/index.ts",
worker: "/src/worker.ts"
},
output: {
filename: "[name].js",
path: path.resolve(__dirname, "build")
},
performance: {
hints: false
},
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
},
]
},
resolve: {
extensions: [".js", ".ts"]
},
plugins: [
new CopyPlugin({
patterns: [
{ from: "src/index.html", to: "" }
]
})
]
};
Yes, It will not work in chorome if your are loading local file. But it will work fine in firefox browser. And you have to add below code in HTML file.
<head>
<meta charset="UTF-8" />
</head>

Categories