SharedWorker Not Working ...much less sharing - javascript

This post is a question which I will answer because I have searched high and low to find an answere to. Its very basic - as basic as you can get when creating a SharedWorker in JavaScript.
I came across an odd problem which has taken me hours to resolve. It was just to get a basic (really) SharedWorker to post a message to the window.
Right now, in my code I am using
...
var port = event.source
...
Everything else is pretty standard across blog articles/tutorials.
Why won't this work?

ANSWER:
I had originally started off on the blog "http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-web-workers/" to do a hello SharedWorker example. DO NOT USE THIS ARTICLE ONLY!!!
The only problem that was holding me back was the that blog "var port = event.source" -- THIS IS INVALID!
USE var port = event.ports[0].
PS. Shared Workers don't have a window object so alert, console.log, etc will not work.
Working code:
index.html:
`<div>
<b>Welcome :)</b>
</div>
<script src="/js/main.js"></script>`
main.js:
var WorkerIO = new SharedWorker('/js/worker.io.js', 'NDN-Worker');
console.log('WorkerIO:', WorkerIO);
WorkerIO.port.addEventListener('message', function(eventM){
console.log('OnMessage:', eventM);
}, false);
WorkerIO.port.start();
WorkerIO.port.postMessage('This is a message from the client!');
WorkerIO.port.addEventListener('error', function(e){
throw new Error('WorkerIO Error: could not open SharedWorker', e);
}, false);
//importScripts();
Worker.io.js:
var ports = [];
self.addEventListener('connect', function(eventC){
'use strict';
ports = eventC.ports;
var port = ports[0];
port.postMessage('WorkerIO: connected');
console.log('o************ OnConnect ************o\n\n'
, '\t ports:', ports, '\n'
, '\t port:', port, '\n'
);
port.addEventListener('message', function(eventM){
var data = eventM.data;
console.log('o************ OnMessage ************o\n\n'
, '\t data:', data, '\n'
);
port.postMessage('from "clientPort": ' + clientPort.toString() + ', with love :)');
}, false);
port.start();
}, false);
Happy coding:)

Related

Get latest message in a chat application - Django

I've coded a chat application with Django Channels and it's working fine. The only issue is getting the latest messages and displaying them when coming back to the chat app. This is resolved for the moment by adding a function that gets older messages (old_messages()) in the chatSocket.onopen = function(e) part of the js file. The only problem now is: when user A refreshes the page of chat, the other user (user B) gets the older messages two times (since the connexion is closed and open for a second time by user A). Any idea how to avoid this problem ?
Here is a part of js file :
var chatSocket = new ReconnectingWebSocket(
'ws://' + window.location.host +
'/ws/chat/' + discussion_slug + '/');
chatSocket.onopen = function(e) {
console.log("open",e)
old_messages();
};
function old_messages() {
chatSocket.send(JSON.stringify({'command': 'old_messages',
'discussion_slug': discussion_slug }));
};
In consumers.py:
def old_messages(self,data):
discussion_slug = Discussion.objects.get(slug=data['discussion_slug'])
last_msgs = discussion_slug.messages.all()[:15]
content = {
'command': 'old',
'message': self.many_msg_to_json(last_msgs)
}
return content
async def receive(self, text_data):
data = json.loads(text_data)
content = self.commands[data['command']](self,data)
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': content
}
)
Thanks!
Have you tried ModelName.objects.all().reverse()? The sorting will be latest first so you might not need old_messages().
If this doesn’t help, let me know. I’ll take a better look once I get on my pc

Send file to Network Printer by Javascript - Acrobat DC

I have a trusted function that saves a file to my network printer. But it doesnt work, I get this error: "The file may be read-only, or another user may have it open. Please save the document with a different name or in a different folder."
This is my code:
var xerox = app.trustedFunction( function()
{
app.beginPriv();
var xeroxPath = "\\\out\\spool\\print\\Xerox\\";
this.saveAs(xeroxPath + this.documentFileName);
app.alert("PDF is sent to the printer",3)
app.endPriv();
});
Ok, I found the solution. In windows map the "\\out\spool\print\Xerox\" to a new network Drive. In my case I mapped it to X: so the code becomes:
var xerox = app.trustedFunction( function()
{ app.beginPriv();
var xeroxPath = "x:\\";
this.saveAs(xeroxPath + this.documentFileName);
app.alert("PDF is sent to the printer",3)
app.endPriv();
});

Email Client in Android using phonegap

I am tryin to use an email client in my application. I am using plugins for the same.
The code that am using is
function tellAFriend()
{
var succcallback = function(result) {
//alert("Mail sent");
};
var errorcallback = function(e) {
//alert("error:" + e);
};
var body1='Hi,\n I came across this new app and thought you might be interested';
var body2=body1+'.You can check it out at \n';
var href1='market';
var anchortext;
anchor1 = document.createElement("a");
anchortext = document.createTextNode('Test');
anchor1.appendChild(anchortext);
anchor1.href=href1;
anchor1.setAttribute('href','https://market.android.com/details?id=com.unisys.cps&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS51bmlzeXMuY3BzIl0');
//alert(anchor1);
window.plugins.webintent.tellAFriend({
mailSubject : 'CPS Mobile App',
mailRecepients: '',
mailBody: href1
//mailBody: 'Hi,\n I came across this new app and thought you might be interested.You can check it out at \nhttps://market.android.com/details?id=com.unisys.cps&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS51bmlzeXMuY3BzIl0 \nor \nhttps://www.cargoportalservices.com/lmsweb/DownloadCPSMobileApp.jsp'
}, succcallback, errorcallback);
}
Thats the function. In the function, the mail body that i have provided needs to be a text. but I need to pass a hyoerlink to it. Meaning, when the email client opens up, the text should be displayed as hyperlinks.
Any suggestions on how that can be achieved.

Channel messaging on HTML 5 with Javascript

I have a problem with the messaging channel in HTML 5
On one side I have the code:
<iframe id="ifr" src="receive.html" onLoad="initMessaging()" ></iframe>
<button onClick="postMsg()">Wyslij</button>
<script type="text/javascript">
var channel = new MessageChannel();
channel.port1.onmessage = function (evt) {
alert(evt.origin + ": " + evt.data);
};
function initMessaging() {
var child = document.getElementById("ifr");
child.contentWindow.postMessage('hello', 'http://localhost:85', [channel.port2]);
}
function postMsg() {
channel.port1.postMessage('Message sent from ' + location.host);
}
And on second site:
<input type="button" value="Post Message" onClick="postMsg();" />
<script type="text/javascript">
var port = null;
window.addEventListener("message", function (e) {
port = e.ports[0];
port.onmessage = function (e){
port.addEventListener("message", function (evt) {alert("Received message \"" + evt.data + "\" from domain: " + evt.origin);
}, false);
}
}, false);
function postMsg() {
if(port) {
port.postMessage("Data sent from " + location.host);
}
Why Its doesnt working? What I do wrong?
Thx a lot for help!
I think you need to use a form to call the postMessage function and send the message. Here's a tutorial that shows a simpler way of getting this done.
HTML5 postMessage interface is not good. I propose an intuitive one. you can download it from my site:
http://www.jackiszhp.info/tech/postMSG.html
window.MSG.post(msgname, msgdata, arrayOfDomainTarget, arrayOfWindowIDTarget)
this 'window' can be omit, not similar to the one specified in HTML5
there you need an window object.
Here, you do not. this 'window' just indicate MSG is in the global space.
msgname is the the name the message category.
msgdata is a JSON object. it will be stringified before post
arrayOfDomainTarget, arrayOfWindowIDTarget
I use logical AND. originally it was OR
later I changed it to AND. more appropriate. I guess.
and I let "*" to be the wildcard for all windowID.
the caller's information does not present in the parameter at all
since the browser knows all the information.
so we can see that this method does not allow the sender to fool the receiver.
the sender just call as follows.
window.name="myWindowID";
MSG.post("cmd",{what:'do thing abc',parameter:'the value of a parameter'},["jackiszhp.info"],[*]);
for the receiver, 2 things.
//#1 define the message handler
function messageHandler(e){
var obj=JSON.parse(e.detail);
obj.name is the msgname = 'cmd'
obj.data is the msgdata = {what:'fuck',who:'not to tell'};
obj.source is the sender
obj.source.href is the sender's window.location.href
obj.source.WID is the sender's window.name="myWindowID";
obj.target is the target of this event
obj.target.domains is the target domains of this event
obj.target.WIDs is the target WIDs of this event
....
}
//#2 register the message handler
window.addEventListener(msgname, messageHandler,false);
or
document.addEventListener(msgname, messageHandler,false);
//to respond,
window.name="hereMywindowID";
MSG.post("cmd",{what:'do thing def',parameter:'the value of a parameter'},["jackiszhp.info"],['myWindowID']);
//clearly, we can see that this response only the original sender can receive it.
//unless in the target domain, accidently, there are two windows with same ID "myWindowID".
Additional note:
A. window can be uniquely identified. but here, I did not use it. I use window.name instead. about window ID, you can check this link: https://developer.mozilla.org/en-US/docs/Code_snippets/Windows#Uniquely_identifying_DOM_windows
B. I hope the mozilla can take my interface and include it into the firefox.

JavaScript talking to Flash via ExternalInterface

I have been trying to put together a proof of concept of JavaScript talking to Flash. I am using JQuery and Flash CS5, ActionScript 3.
I am not a Flash developer so apologies for the code, if I can prove this works the Flash will be given to someone who knows what they are doing.
The Actionscript is on a layer in the timeline in the first frame, with a couple of elements in the root movie:
output = new TextField();
output.y = -200;
output.x = -200;
output.width = 450;
output.height = 325;
output.multiline = true;
output.wordWrap = true;
output.border = true;
output.text = "Initializing...\n";
root.bgClip.addChild(output);
try{
Security.allowDomain("*");
flash.external.ExternalInterface.marshallExceptions = true;
output.appendText("External Interface Available? " + ExternalInterface.available + "\n");
output.appendText("External Interface ObjectId: " + ExternalInterface.objectID + "\n");
flash.external.ExternalInterface.addCallback("getMenuItems", returnMenuItems);
flash.external.ExternalInterface.addCallback("changeText", changeText);
flash.external.ExternalInterface.addCallback("changeBgColour", changeBgColour);
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
} catch (error:SecurityError) {
output.appendText("Security Error: " + error.message + "\n");
} catch (error:Error) {
output.appendText("Error: " + error.message + "\n");
}
function returnMenuItems():String{
return "[{\"menu option\": \"javascript:callFlash('changeBgColour','4CB9E4')\"}]";
}
function changeText(t:String){
root.textClip.text = t;
}
function changeBgColour(colour:String) {
var c:ColorTransform = root.bgClip.transform.colorTransform;
c.color = uint(colour);
root.bgClip.transform.colorTransform = c;
}
The JavaScript and HTML are:
function populateMenu(message){
$("#options").changeType("Options", $.parseJSON(message));
$("#options").addMenuActions();
}
function callFlash(methodToCall, param){
alert("method: " + methodToCall + ", param: " + param);
if(param == undefined){
$("#AJC")[methodToCall]();
}else{
$("#AJC")[methodToCall](param);
}
}
var flashvars = {};
var params = {allowScriptAccess: "always"};
var attributes = {name: "AJC"};
swfobject.embedSWF("http://192.168.184.128/ActionscriptJavascriptCommunication.swf", "AJC", "600", "400", "9", "", flashvars, params, attributes);
and
<body>
<div id="wrapper">
<div id="topBar" class="top-bar"></div>
<div id="flashContainer">
<div id="AJC">Loading Flash...</div>
</div>
<ul class="dropdown" id="games"></ul>
<ul class="dropdown" id="options"></ul>
</div>
</body>
Now I know the ActionScript is awful, the reason it looks like it does is because I have read a lot of threads about possible issues to do with contacting Flash from JavaScript (hence the allow security domain * and adding a debug text box etc).
The JavaScript I am using is within a script tag in the head. The changeType and addMenuActions are just JQuery methods I have added. These are just JavaScript methods that have been tested independently but do work.
You'll notice that the last line of my try catch in the ActionScript is:
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
This does work, it populate my menu with the text sent from Flash. The only thing that doesn't work is trying to call the methods exposed using the addCallback function.
I get the alert which says:
method: changeBgColour, param: 4CB9E4
but an error saying:
Error: $("#AJC")[methodToCall] is not a function
Source File: http://192.168.184.128/test.html#
Line: 88
I set up a local VM to run Apache, which relates to the 192.168.184.128, I wondering if this was the issue, I have seen a couple of threads mention that trying to communicate with flash locally won't work, which is why I set up the VM with apache?
Any ideas? I know people have got this working, it is very frustrating.
Thanks.
Simple mistake: jQuery's factory method produces jQuery.init object, which acts very similar to an array. You need to call the method on the actual DOM element, which is the first member in the "array".
$('#AJC')[0][methodToCall]
If you had security issues, you wouldn't be able to communicate between Flash and JavaScript at all.
The problem is in the way you are accessing your flash object. SwfObject has a built-in function that take care of that, it works great across all browsers:
function callFlash(methodToCall, param)
{
var obj = swfobject.getObjectById("AJC");
if(param == undefined){
$(obj)[methodToCall]();
}else{
$(obj)[methodToCall](param);
}
}
I havent tested the code above, but I guess it should work!

Categories