Why don't web workers work? - javascript

So, I'm trying to use a web worker in my project to run a long-running process that is currently tying up the UI. I've been to I don't know how many sites trying to get a worker to work, but to no avail.
All of my javascript is kept in separate files and referenced in the HTML file. As a test to get my feet wet, I created a test.js file and put the following code in it:
self.addEventListener('message', function(e) {
self.postMessage('return');},false);
Then, in the UI page's javascript file I placed this code in a function triggered by a button click event:
var w = new Worker('test.js');
w.addEventListener('message',function(e){
alert(e.data);},false);
w.postMessage('hi');
The code is derived from:
html5rocks.com/en/tutorials/workers/basics
Other websites I visited provided similar instructions on how to set up a worker.
For the life of me, I cannot get this to work. When I execute it does absolutely nothing and I seemingly get no errors. Stepping through the code, it appears to create the worker, but I don't see any evidence of the event listener being created and the 'postMessage' event doesn't do anything. I've tried IE11 and Chrome with the same results.
In my research, I came across a part of Chrome's developer tools that revealed the test.js file couldn't be found. Yet, the file is in the same folder as the page's js file. So, I tried adding in the relative directory information as I do in the page's HTML section. That didn't work either.
I then found claims that for security reasons you couldn't have one js file reference another js in the code. It's unclear whether this is a Chrome-only feature or part of some spec.
So, now I'm in a quandary. The worker requires a reference to a separate js file for the code to be executed, yet, the browser isn't allowed to reference another file? How is the worker supposed to work if you aren't allowed to do what it requires to work?
To now, I've successfully pissed away two days trying to get this one seemingly simple function to work. To say I'm mildly frustrated would be an understatement. Being a fairly novice programmer and not understanding every last little nuance about web programming I'm clearly missing a key part of this whole thing.
How the heck is one supposed to make web workers work?

Turns out browsers won't allow local files to be fetched via javascript. Because that means a website can read your personal files! So you need to develop and test your project using a web server. The easiest way to do this for me was to install:
docker-compose
and make sure it works. Then create a file named:
docker-compose.yml
inside root folder of my project with index.html file. Then put this inside the docker-compose.yml file:
version: '3'
services:
nginx:
image: nginx:alpine
volumes:
- .:/usr/share/nginx/html
ports:
- "80:80"
Then inside the root folder of my project run:
docker-compose up
And then in the browser go to:
http://localhost/
And it worked!

I appear to have found a solution, though it escapes me why.
If I use:
var w = new Worker('js\test.js');
the worker doesn't work.
But, if I use:
var w = new Worker('js/test.js');
the worker does work.
I characteristically use the back slash throughout the project to delineate paths without issue. Why the forward slash must be used to set the worker's file location is a mystery. I have seen nothing in any documentation that even remotely addresses that tiny, yet seemingly critical detail.
Thank you, Mr. Starke, for your help!

Related

how do you allow javascript communications with Flex/Flash/Actionscript

Well here's a problem.
I've got a website with large javascript backend. This backend talks to a server over a socket with a socket bridge using http://blog.deconcept.com/swfobject/
The socket "bridge" is a Flex/Flash .swf application/executable/plugin/thing for which the source is missing.
I've got to change it.
More facts:
file appExePluginThing.swf
appExePluginThing.swf Macromedia Flash data (compressed), version 9
I've used https://www.free-decompiler.com/flash/ to decompile the .swf file and I think I've sorted out what's the original code vs the libraries and things Flash/Flex built into it.
I've used FDT (the free version) to rebuild the decompiled code into MYappExePluginThing.swf so I can run it with the javascript code and see what happens.
I'm here because what happens isn't good. Basically, my javascript code (MYjavascript.js) gets to the point where it does
window.log("init()");
var so = new SWFObject("flash/MYappExePluginThing.swf"", socketObjectId, "0", "0", "9", "#FFFFFF");
window.log("init() created MYappExecPluginThing!!!");
so.addParam("allowScriptAccess", "always");
log("init() added Param!!");
so.write(elId);
log("init() wrote!");
IE9's console (yeah, you read that right) shows
init()
created MYappExecPluginThing!!!
init() added Param!!
init() wrote!
but none of the debugging i've got in MYappExePluginThing.as displays and nothing else happens.
I'm trying to figure out what I've screwed up/what's going on? Is MYappExePluginThing.as running? Is it waiting on something? Did it fail? Why aren't the log messages in MYappExePluginThing.as showing up?
The first most obvious thing is I'm using FDT which, I suspect, was not used to build the original. Is there some kind of magic "build javascript accessible swf thing" in FlashBuilder or some other IDE?
First noteworthy thing I find is:
file MYappExePluginThing.swf
MYappExePluginThing.swf Macromedia Flash data (compressed), version 14
I'm using Flex 4.6 which, for all I know, may have a completely different mechanism for allowing javascript communication than was used in appExePluginThing.swf
Does anyone know if that's true?
For example, when FDT runs this thing (I can compile but FDT does not create a .swf unless i run it) I get a warning in the following method:
private function init() : void
{
Log.log("console.log", "MYappExePluginThing init()");
//var initCallback:String = Application.application.parameters.initCallback?Application.application.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
var initCallback:String = FlexGlobals.topLevelApplication.parameters.initCallback?FlexGlobals.topLevelApplication.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
try
{
ExternalInterface.addCallback("method1Callback",method1);
ExternalInterface.addCallback("method2Callback",method2);
ExternalInterface.call(initCallback);
}
catch(err:Error)
{
Log.log("console.log", "MYappExePluginThing init() ERROR err="+err);
}
}
I got a warning that Application.application was deprecated and I should change:
var initCallback:String = Application.application.parameters.initCallback?Application.application.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
to:
var initCallback:String = FlexGlobals.topLevelApplication.parameters.initCallback?FlexGlobals.topLevelApplication.parameters.initCallback:"MYjavascript.MYappExePluginThing_init";
which I did but which had no effect on making the thing work.
(FYI Log.log() is something I added:
public class Log{
public static function log(dest:String, mssg:String):void{
if(ExternalInterface.available){
try{
ExternalInterface.call(dest, mssg);
}
catch(se:SecurityError){
}
catch(e:Error){
}
}
trace(mssg);
}
}
)
Additionally, in MYjavascript.js MYappExePluginThing_init looks like this:
this.MYappExePluginThing_init = function () {
log("MYjavascript.js - MYappExePluginThing_init:");
};
Its supposed to be executed when MYappExePluginThing finishes initializing itself.
Except its not. The message is NOT displaying on the console.
Unfortunately, I cannot find any references explaining how you allow javascript communication in Flex 4.6 so I can check if I've got this structured correctly.
Is it a built in kind of thing all Flex/Flash apps can do? Is my swf getting accessed? Is it having some kind of error? Is it unable to communicate back to my javascript?
Does anyone have any links to references?
If this was YOUR problem, what would you do next?
(Not a full solution but I ran out of room in the comment section.)
To answer your basic question, there's nothing special you should need to do to allow AS3-to-JS communication beyond what you've shown. However, you may have sandbox security issues on localhost; to avoid problems, set your SWFs as local-trusted (right-click Flash Player > Global Settings > Advanced > Trusted Location Settings). I'm guessing this not your problem, though, because you'd normally get a sandbox violation error.
More likely IMO is that something is broken due to decompilation and recompilation. SWFs aren't meant to do that, it's basically a hack made mostly possible due to SWF being an open format.
What I suggest is that you debug your running SWF. Using break-points and stepping through the code you should be able to narrow down where things are going wrong. You can also more easily see any errors your SWF is throwing.
Not really an answer, but an idea to get you started is to start logging everything on the Flash side to see where the breakage is.
Since you're using IE, I recommend getting the Debug flash player, installing it, then running Vizzy along side to show your traces.
Should give you a good idea of where the app is breaking down.
Vizzy
Debug Player

How do I change the underlying Phantomjs object settings using Chutzpah?

We have some QUnit javascript tests running in Visual Studio using the Chutzpah test adapter. Everything was working fine until we changed our api (the one being tested by the js files) recently, and added some validations over the UserAgent http header. When I tried to update the tests to change/mock the user agent I realized it was not directly possible even by overriding the default browser property.
After a few days of scavenging, I finally found what exactly is happening. Chutzpah is creating a phantomjs page object for the test files to run on. This is being done on a base javascript file (chutzpahRunner.js) located at the Chutzpah adapter installation path. These are the last lines on the file, that effectively start the tests:
...
// Allows local files to make ajax calls to remote urls
page.settings.localToRemoteUrlAccessEnabled = true; //(default false)
// Stops all security (for example you can access content in other domain IFrames)
page.settings.webSecurityEnabled = false; //(default true)
page.open(testFile, pageOpenHandler);
...
Phatomjs supports changing the user agent header by specifying it in the page settings object. If I edit this chutzpahRunner.js file in my machine, and manually set the user agent there, like this:
page.settings.userAgent = "MyCustomUserAgent";
My tests start to work again. The problem is that this is not in the project itself, and thus cannot be shared with the rest of the team.
Is it possible to change the properties of the phantomjs objects created by Chutzpah to run the tests? I'd like to either change them from inside my own tests, or from another script file I could embed on the pipeline.
Without a code change in Chutzpah it is not possible to set those properties on the PhantomJS object. Please file an issue at https://github.com/mmanela/chutzpah asking for this functionality and then fork/patch Chutzpah to add it (or wait for a developer on the project to hopefully get to this).
Update:
I pushed a fix for this issue. Once this is released you can use the following in a Chutzpah.json file:
{
"userAgent": "myUserAgent"
}

Dart Editor: Pub build produces dysfunctional files

I'm working on a dart thing. Everything works flawlessly when I test it in Dartium. But when I Pub Build the project and run the .html file in the build/web folder, everything that's dart gets completely ignored.
I thought the problem might be in my code, but this does not seem to be the case since I don't even need to write any. It's enough if I just create a new project from the 'Web application' template and keep the template code in there (you know, the one with a "Click me!" text that reverses if you click it).
I get no errors while building the project. I build the project by right-clicking on pubspec.yaml and choosing the 'Pub Build (generates JS)' - Is this the right way of doing it, or am I doing something wrong?
Indeed, it was caused by the missing dart.js in the "packages/browser"
Running the 'pub cache repair' command was sufficient in bringing the missing file back and now everything works.

WScript is undefined

I am trying to run a Javascript file locally, which is supposed to create a CSS image sprite using ImageMagick. It's part of the OpenID selector JS component: http://code.google.com/p/openid-selector/
The generate-sprite.js (http://code.google.com/p/openid-selector/source/browse/trunk/generate-sprite.js?r=140) file is supposed to create the image sprite automatically. However, whenever I run it in IE (the local version of the file, of course), I get the error SCRIPT5009: 'WScript' is undefined on line 19, character 1.
I have of course installed ImageMagick and updated the location in the js file. IE9 is letting the ActiveX execute.
Since I'm not familiar with WScript, I am completely lost. Googling didn't help, since this seems to be a very generic error.
Can somebody help diagnose this error please?
When you say you're "running" the JavaScript file locally, are you using Windows? If so, and double-clicking or typing the filename from the command line doesn't work, try:
wscript generate-sprite.js
...which explicitly invokes wscript.exe.
If you're not using Windows, you can't use that script — it relies on both Windows and Microsoft's JScript (which the wscript.exe program invokes).

path- and other problems using node.JS and Socket.IO

I'm using node.JS in VirtualBox on a TurnkeyLinux hosted by Windows. I was following the instructions here. node.JS is living in /root/node. Although I can run simple examples successfully I'm having a hard time figuring out certain things, cause I'm not a Linux-guy normally. I wanted to use socket.io.
I managed installing node.JS itself using git and tried that with Express and Socket.IO too. (e.g. git clone git://github.com/LearnBoost/Socket.IO.git). It seems to work, but I can't find that stuff anywhere! Was in /root/node when calling git, expecting changes in the lib-folder...
node.JS is using the CommonJS module system. In the Socket.IO example io = require('../') is used to import Socket.IO which looks pretty strange to me. Other expamples on the web are referring to './Socket.IO-node'. As a module is just a JS-file following certain rules I would expect sth like a path to such a file, as I found http.js in /root/node/lib.
By the way, looking at the server.js example: Is there a certain reason using var for http, but not for the rest of the variables (url, fs, io, sys)?
On clientside the first line on "How to use" Socket.IO is: io.setPath(...). setPath is not mentioned anywhere else on the page. Where should it point to, relative to what?
I've found no information about stoping/restarting node using the shell. Probably it's so obvious, that it's never mentioned anywhere ;)
Thanks for helping out.
The git-version that comes with the Turnkey-Core these days is quite outdated. Maybe this is causing problems. I worked around using my git on windows and WinSCP ;)
There is an inbuild automatism that index.js is used by default like index.html is used by default on webservers. So '../' is pointing to index.js in the parent folder, which then exports the listener of socket.io. Guillermo Rauch has put an index.js in the socket.io-folder now, so sth like './lib/socket.io/' is working. Note that there are examples out there with sth like './socket.io/socket.io.js', but socket.io.js doesn't exist anymore for some good reasons.
Of course the var is used for all variables. I've seen the commas as semicolons. Maybe I should change my screen-resolution ;)
It comes clear when looking at the example. setPath points to the folder where socket.io.js and it's lib-directory lives, relative to the html-file that uses it. This is needed for the flash-sockets to work.
Well, it's not that simple. You may look up the PID usind 'ps ux' and then 'kill' the process using the PID. A better way is using upstart. Or you do it by code using autorestart.

Categories