Git Product home page Git Product logo

jschannel's Introduction

Welcome to JSChannel

JSChannel is a small JavaScript abstraction layer on top of HTML5 cross document messaging. It builds rich messaging semantics out of postMessage.

Overview

HTML5's cross document messaging opens up a ton of possibilities for interesting client side creations. But, the specification only provides the bare minimum amount of plumbing required to support cross domain client side communication. JSChannel is a very small abstraction that provides higher level messaging semantics on top of postMessage, which include:

  • Query/Response - including support for callback arguments
  • Notifications - Fire and forget style.

In addition to support for these messaging semantics, the library sports the following additional features:

  • "scoping", all messages will be safely tucked under the namespace you provide.
  • multiple channel support - message handling properly stops propagation once messages are handled, and when they're not it leaves them alone. This means you can have an arbitrary number of different channels in a single page.
  • Rich messaging semantics - Query/Response and Notifications
  • An idiomatic api - exceptions inside message handlers automatically turn into error responses. return values are likewise converted into "success" responses.
  • support for errors: the library provides the basic structure for error propagation while the client define error codes.
  • very compatible with asynchronicity.
  • supports any browser with JSON parsing (native or as a JS library) and postMessage.
  • designed primarily for inter-frame communication.

Sample usage

The simplest possible use case. A client (parent.html) loads up another document in an iframe (child.html) and invokes a function on her.

parent.html

<html>
<head><script src="src/jschannel.js"></script></head>
<body>
<iframe id="childId" src="child.html"></iframe>
</body>
<script>

var chan = Channel.build({
    window: document.getElementById("childId").contentWindow,
    origin: "*",
    scope: "testScope"
});
chan.call({
    method: "reverse",
    params: "hello world!",
    success: function(v) {
        console.log(v);
    }
});

</script>
</html>

child.html

<html><head>
<script src="src/jschannel.js"></script>
<script>

var chan = Channel.build({window: window.parent, origin: "*", scope: "testScope"});
chan.bind("reverse", function(trans, s) {
    return s.split("").reverse().join("");
});

</script>
</head>
</html>

Documentation

Full documentation for JSChannel can be found here.

Influences

JSON-RPC provided some design inspiration for message formats.

The existence of pmrpc inspired me there's room for pure js abstractions in this area.

The API design was influenced by postmessage.

LICENSE

All files that are part of this project are covered by the following license. The one exception is code under test/doctestjs which includes licensing information inside.

Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version 
1.1 (the "License"); you may not use this file except in compliance with 
the License. You may obtain a copy of the License at 
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

The Original Code is jschannel.

The Initial Developer of the Original Code is Lloyd Hilaiel.

Portions created by the Initial Developer are Copyright (C) 2010
the Initial Developer. All Rights Reserved.

Contributor(s):

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.

jschannel's People

Contributors

brianloveswords avatar edsu avatar jmandel avatar lloyd avatar toolness avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jschannel's Issues

JSON.stringify and Prototype

I ran into some strange list flattening behavior when objects were passed over the channel, and tracked it down to Prototype changing the behavior of JSON.stringify which is discussed here. The app I am working on is injected into pages outside of my control, so I need to make sure that Prototype's JSON.stringify isn't being used.

My question is, does it make sense for jschannel to make sure that this broken JSON.stringify from Prototype isn't being used accidentally, to save other people the heartache of tracking down this problem? Or is this something that I should do in my app?

Origin Use is Backwards?

I have a page which loads an iframe from a user configured URL. In order to set up the channel between the page and the iframe, I initialize the channel each using the other's URL, after reducing it to protocol://domain/.

For example, page at http://localhost/a/b/c loads external website http://think.dolhub.com. So in the localhost page I use origin="http://think.dolhub.com" and in the external page on dolhub.com I use origin="http://localhost".

However, the request to build the channel throws: Failed to execute ‘postMessage’ on ‘DOMWindow’: The target origin provided (‘http://think.dolhub.com’) does not match the recipient window’s origin (‘http://localhost’).. However, the supplied origin most certainly does match the recipient's origin:

image

This is backwards from my expectations, which is to supply the origin of the page I wish to communicate with at each respective end. Otherwise, where is the security?

jshannel origin is case-sensitive (while window.postMessage origin is not)

The behavior of window.postMessage is to extract an origin from the URI provided, such that I can do either of the following:

  1. target.postMessage("A message", "http://someORIGIN.com");
  2. target.postMessage("A message", "http://someorigin.com");

... but since Channel.build uses the origin parameter as the key to an associative array, if I build a channel with scope http://someORIGIN.com, it will fail to receive messages with event.origin=="http://someorigin.com".

It might be worth normalizing the origin URI passed into Channel.build, e.g. by calling toLowerCase(). Does this open up other issues I haven't thought of? Sample patch below.

-Josh


From a50048a86d9022e34b66f50b831386e14b8a55f2 Mon Sep 17 00:00:00 2001
From: Josh Mandel 
Date: Mon, 23 May 2011 11:34:53 -0700
Subject: [PATCH] normalize channel origin to lower-case

---
 src/jschannel.js |    2 +-
 1 files changed, 1 insertions(+), 1 deletions(-)

diff --git a/src/jschannel.js b/src/jschannel.js
index 6e6f6c0..f7a639e 100644
--- a/src/jschannel.js
+++ b/src/jschannel.js
@@ -248,7 +248,7 @@
                 if (cfg.origin === "*") validOrigin = true;
                 // allow valid domains under http and https.  Also, trim paths off otherwise valid origins.
                 else if (null !== (oMatch = cfg.origin.match(/^https?:\/\/(?:[-a-zA-Z0-9\.])+(?::\d+)?/))) {
-                    cfg.origin = oMatch[0];
+                    cfg.origin = oMatch[0].toLowerCase();
                     validOrigin = true;
                 }
             }
-- 
1.7.4.1

Add a LICENSE file

This Mozilla repository has been identified as lacking a LICENSE.md file. This repository does have licensing information in the README.md file. To make it easier for users (and scanning tools) to find licensing information please add a LICENSE.md file with that information to the root directory of the project.

Mozilla staff can access more information in our Software Licensing Runbook – search for “Licensing Runbook” in Confluence to find it.

If you have any questions you can contact Daniel Nazer who can be reached at dnazer on Mozilla email or Slack.

READMELIC-2023-01

Add JSChannel to npm

Hey. Why don't you add JSChannel to npm? Any problems with this package manager.

I like this library and I would like to use it with webpack without copy a file manually.

recursive data structure in params

I accidentally passed a recursive data structure to call, and got an exception that took me some time to understand:

chan.call({
  method: "highlight",
  params: window.getSelection(),
  success: function(v) {
    console.log("highlighted " + v);
  }
});

Which results in:

Uncaught RangeError: Maximum call stack size exceeded

due to an infinite recursion in pruneFunctions.

CODE_OF_CONDUCT.md file missing

As of January 1 2019, Mozilla requires that all GitHub projects include this CODE_OF_CONDUCT.md file in the project root. The file has two parts:

  1. Required Text - All text under the headings Community Participation Guidelines and How to Report, are required, and should not be altered.
  2. Optional Text - The Project Specific Etiquette heading provides a space to speak more specifically about ways people can work effectively and inclusively together. Some examples of those can be found on the Firefox Debugger project, and Common Voice. (The optional part is commented out in the raw template file, and will not be visible until you modify and uncomment that part.)

If you have any questions about this file, or Code of Conduct policies and procedures, please reach out to [email protected].

(Message COC001)

Enhancement: should print out stacktrace of caught exceptions in debug mode.

I suggest a very simple, yet (IMHO) very helpful suggestions. I was using jschannel for notification and the function which it've called had an obvious error in it, but jschannel quietly ate the exception, even in debug mode, and the only error it gave back is a "runtime_error" string, which is far from being helpful.

After inspecting the code, I think adding a simple console.log(e.stack) or something similar (only in debug mode) here: https://github.com/mozilla/jschannel/blob/master/src/jschannel.js#L390
would help a great deal when debugging.

Channel setup fails silently

When I bind to a channel in an iframe, and the iframe doesn't implement jschannel at all, I believe the result is just silent failure (at least, I've gotten a silent failure and I think this is why). An explicit error would be much nicer. (There's been lots of head banging on my part lately I think due to several overlapping silent errors.)

Can't connect to PDF.js pages

When trying to connect to a PDF.js environment, I get this:

"Channel.build() called with an invalid origin"

The reason is that only http:// and https:// domains are allowed by default.
This should be extended to involve PDF.js.

Timeout

It would be nice if any jschannel call could have a timeout argument, since exceptions don't seem to be entirely reliable. A timeout would call the error callback with a Timeout argument/exception.

A late-arriving response would have to be figured out; call the error callback with a LateResponse object with an attribute indicating the response?

ready message has a race condition

The code transmitting "ready!" assumes that it may never receive a ready signal from the opposite side when it is ready.
Normally, this is OK, and the flow is roughtly:

(A) comes online, sends "ping"
(B) not online yet, "ping" lost.
(B) comes online, sends "ping"
(A) receives B's ping; ready=true; sends "pong"
(B) receives A's pong; ready=true

However, this assumption can fail when A+B come online around the same time:

(A) comes online, sends "ping"
(B) comes online, sends "ping"
(B) receives A's ping; ready=true; sends "pong"
(A) receives B's ping; ready=true; sends "pong"
(B) receives A's pong but is ready throws exception
(A) receives B's pong but is ready throws exception

Notably, this can happen because there's no guarrantee of a single thread of execution across windows/frames/web-worker, and even if there were, there is no guarrantee that execution of a postMessage handler is immediately after the sending of a message - there may simply be non-stop execution or other event handers which cause (B) to come online before the message is handled.

Fix: don't throw an exception when this happens.

if scope is omitted, silent failures ensue

If we set up a jschannel without a scope, no communication occurs, nor do errors. Annoying and unexpected. Should either explicitly require scope or if it remains optional, create a default automagically.

callbacks needed for debugger support

it would be good to be able to hook a function into jschannel that's invoked immediately before a message is posted, and immediately when one is received.

Suggested implementation is to change the signature of build to take an object (named arguments)

var chan = Channel.build({
    origin: "*",
    onPostMessage: function(origin, msg) { ...},
    onMessageReceived: function(origin, msg) { ...},
    scope: "whatever",
    window: document.getElementById("theIFrame").contentWindow
});

messages with a result of 0 are ignored

could this be loose interpretation of falsey values?

Specifically, when a message arrives with a valid id and a result parameter with a value of zero it doesn't seem to make it past the checks in the onMessage handler.

make it smaller?

the debug statements and verbose thrown strings are really nice for developer ergonomics, but do have a negative effect on size. currently yui compressed and gzipped the lib is 2.6k... Think about whether its worth shedding some of that verbosity for size benefit?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.