GithubHelp home page GithubHelp logo

krakenjs / zoid Goto Github PK

View Code? Open in Web Editor NEW
2.0K 44.0 245.0 39.26 MB

Cross domain components

License: Apache License 2.0

HTML 0.16% JavaScript 99.83% Shell 0.01%
component angular react popup iframe iframes ember cross-domain hacktoberfest

zoid's Introduction

zoid


build status code coverage npm version

A cross-domain component toolkit, supporting:

  • Render an iframe or popup on a different domain, and pass down props, including objects and functions
  • Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions
  • Create and expose components to share functionality from your site to others!
  • Render your component directly as a React, Vue or Angular component!

It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups!


Public options and methods supported by zoid

Working demos of different zoid patterns

Forkable demo app with build, test, publishing and demos pre-configured.

A full example of a cross-domain component using zoid


Quick example

Define a component to be put on both the parent and child pages:

var MyLoginComponent = zoid.create({
  tag: "my-login-component",
  url: "http://www.my-site.com/my-login-component",
});

Render the component on the parent page:

<div id="container"></div>

<script src="script-where-my-login-component-is-defined.js"></script>
<script>
    MyLoginComponent({

        prefilledEmail: '[email protected]',

        onLogin: function(email) {
            console.log('User logged in with email:', email);
        }

    }).render('#container');
</script>

Implement the component in the iframe:

<input type="text" id="email" />
<input type="password" id="password" />
<button id="login">Log In</button>

<script src="script-where-my-login-component-is-defined.js"></script>
<script>
    var email = document.querySelector('#email');
    var password = document.querySelector('#password');
    var button = document.querySelector('#login');

    email.value = window.xprops.prefilledEmail;

    function validUser (email, password) {
      return email && password;
    }

    button.addEventListener('click', function() {
        if (validUser(email.value, password.value)) {
            window.xprops.onLogin(email.value);
        }
    });
</script>

Useful Links

Framework Specific

Rationale

Writing cross domain components is tricky.

Consider this: I own foo.com, you own bar.com, and I have some functionality I want to share on your page. I could just give you some javascript to load in your page. But then:

  • What if I've written a component in React, but you're using some other framework?
  • What if I have secure form fields, or secure data I don't want your site to spy on?
  • What if I need to make secure calls to my back-end, without resorting to CORS?

What about an iframe?

You could just use a vanilla iframe for all of this. But:

  • You have to pass data down in the url, or with a post-message.
  • You need to set up post-message listeners to get events back up from the child.
  • You need to deal with error cases, like if your iframe fails to load or doesn't respond to a post-message.
  • You need to think carefully about how to expose all this functionality behind a simple, clear interface.

zoid solves all of these problems.

  • You pass data and callbacks down as a javascript object
  • zoid renders the component and passes down the data
  • The child calls your callbacks when it's ready

It will even automatically generate React and Angular bindings, so people can drop-in your component anywhere and not worry about iframes or post-messages.

FAQ

  • Do I need to use a particular framework like React to use zoid?

    No, zoid is framework agnostic. You can:

    • Use it with vanilla javascript.
    • Use it with any framework of your choice.
    • Use it with React or Angular and take advantage of the automatic bindings on the parent page
  • Why write another ui / component library?

    This isn't designed to replace libraries like React, which are responsible for rendering same-domain components. In fact, the only real rendering zoid does is iframes and popups; the rest is up to you! You can build your components using any framework, library or pattern you want, then use zoid to expose your components cross-domain. It should play nicely with any other framework!

  • Aren't iframes really slow?

    Yes, but there are a few things to bear in mind here:

    • zoid isn't designed for building components for your own site. For that you should use native component libraries like React, which render quickly onto your page. Use zoid to share functionality with other sites, that you can't share native-javascript components with

    • zoid also provides mechanisms for pre-rendering html and css into iframes and popups, so you can at least render a loading spinner, or maybe something more advanced, while the new window loads its content.

  • I don't want to bother with popups, can I get zoid with just the iframe support?

    You can indeed. There's an zoid.frame.js and zoid.frame.min.js in the dist/ folder. There's a lot of magic that's needed to make popups work with IE, and that's all trimmed out.

  • Can I contribute?

    By all means! But please raise an issue first if it's more than a small change, to discuss the feasibility.

  • Is this different to react-frame-component?

    Yes. react-frame-component allows you to render html into a sandboxed iframe on the same domain. zoid is geared around sharing functionality from one domain to another, in a cross-domain iframe.

Browser Support

  • Internet Explorer 9+
  • Chrome 27+
  • Firefox 30+
  • Safari 5.1+
  • Opera 23+

zoid's People

Contributors

7006 avatar anthonykhoa avatar bluepnume avatar copperwall avatar crookedneighbor avatar daton89 avatar dtjones404 avatar freshfunkee avatar gillycheesesteak avatar gregjopa avatar harouny avatar joshgreenwell avatar leogedler avatar mcntsh avatar mikegrassotti avatar mmairs9 avatar mnicpt avatar mstuart avatar namirsab avatar nicolasmontone avatar olehrb avatar oscarleonnogales avatar r0stig avatar ramasilveyra avatar rubenfig avatar shrutikapoor08 avatar snaheth avatar vishakha94 avatar westeezy avatar wsbrunson 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  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

zoid's Issues

Firefox - renderToParent - focus does not work

Calling .focus() does not work from a different frame, in Firefox. Mainly relevant for .renderToParent() cases.

The problem is (I believe) that the focus call is happening asynchronously after the button click, since there's a post message being sent to do the focus.

Somehow this isn't an issue in other browsers. Go figure.

Could potentially fix this by getting a handle on the window. But that isn't easy in IE -- using the var win = window.open('', winName); trick doesn't work particularly well cross-domain.

Would rather not do this with if (isFirefox()) { ... }...

Add a ping / keepalive

So the parent can optionally error out if the child redirects or stops being responsive.

Domain restriction

I should be able to restrict a component to only run on a certain url / url pattern.

Need to think about how to implement this, and if there's any reliable client side way to ensure I'm being rendered from a certain domain.

Namespace CSS

We should namespace all CSS under an autogenerated component id, to prevent conflicts.

Do not pass down some props

By default all props (except functions) are serialized and passed down in the url. I should be able to specify props which are not passed down in the url.

For example:

myProp: {
    type: 'string',
    url: false
}

Also certain built-in props (like url) should not be passed down by default.

Better handling of async errors in tests

Right now, because so much is async/callback based, we don't actually catch a lot of errors in our tests, they just fail and timeout. Is there a way to do testing better when we have multiple async callbacks that all rely on postMessages? Can we direct all errors into a single rejected promise or something?

How to trigger a function in Child's window from Parent's window

Is it possible to access a global function defined in the child's window from the parent's window object? Does xcomponent or postRobot have this feature built in?

The use case is, when a user clicks a button in the parent component, I want the child component to respond to the click.

Thanks!

Auto-attach child

  • pass down props in window.name, with methods serialized
  • detect current component, auto-attach

Way to determine the render context on the fly

There are situations where we need to figure out what render context we want to use, on the fly in the parent page.

For example: for PayPal Checkout, if the user is one-touch logged in, we render checkout in a lightbox iframe, otherwise we use a popup window.

One possibility is to add a method like:

determineContext() {
    return someContextDeterminingPromise();
}

The only problem with this is it begins to add runnable code / logic to the parent page, which I'm not sure if we want to do for xcomponent

Way to specify different urls based on the device type

I'd like to be able to have components pick different urls based on, for example, whether they are mobile/desktop or potentially other differences.

Right now we only support url differences based on env.

One possibility is to add a devieUrls.

Another is to allow url to be a function which would let the component author determine the logic for deciding on the url. But this releases the 'running custom javascript on the parent' cat out of the bag.

Expose exports from child

On the child window:

window.xchild.exports.foo = function() { ... };

On the parent:

this.exports.foo();

Also need a way to declare this on the component definition, so we can mock out function calls until the child is ready.

Allowing javascript on the parent?

The way I've been designing this so far is to prevent any custom javascript from running on the parent site.

This makes it safer for component users, because they can see that the only code they're running is:

  1. xcomponent, which is open source and unlikely to contain vulnerabilities
  2. A small custom component definition which (as of now) contains no logic or runnable code, and could even just be serialized json.

But allowing parent-side logic is becoming more and more necessary, for features like:

And probably other future features.

Is there a way to mitigate this? I'd love to keep some of this executable logic in the child window, but the issues above are both things we need to know before we can even begin to render.

Also we're limited to having to do a lot synchronously, since if the component author wants to render a popup, we have to do everything in the same frame as the button click.

Thoughts?

Auto-resizing of parent

I should be able to specify autoResize: true and have my lightbox automatically resize itself to match the size of the child window body size.

For example

let FooComponent = xcomponent.create({
    ...
    autoResize: true
});

Should probably use a setInterval loop in the child and postMessage up to resize if the document.body size changes.

Note -- unless we can find a way to resize popup windows outside of user interaction events, this is probably just going to have to be limited to lightboxes.

CI Job for tests on github

  • Set up some kind of CI system -- Travis?
  • Run gulp test for every PR
  • Get tests working/running in popular browsers, including IE
  • Saucelabs for the karma tests in multiple browsers?

sameDomain props

  • Do not send to child on different domain
  • Do not accept on child on different domain

Auto set up post-robot bridge

I should be able to pass the post-robot bridge url into an xcomponent definition, and have it automatically set up the bridge for me on the parent page when the component loads.

For example:

let FooComponent = xcomponent.create({
    ...
    postMessageBridge: 'http://foo.com/bar/bridge'
});

Add beaver logs

We should use beaver-logger to instrument xcomponent, and allow people to pass in their own beaver back-end url, for example:

let FooComponent = xcomponent.create({
    ...
    logUrl: 'http://foo.com/api/log'
});

Make angular integration less hacky

Right now we're monkey patching angular to get the directive auto-attached.

Let's not do this. It would be better to have the user have to include a custom angular module prior to bootstrap.

Simplify the number of stylesheets and templates we have.

Right now we provide:

  • parentStyleSheet
  • overlayStyleSheet
  • overlayTemplate
  • componentStyleSheet
  • componentTemplate

Thinking we should whittle these down to (at least)

  • parentStyleSheet
  • parentTemplate
  • componentStyleSheet
  • componentTemplate

and have the overlay encapsulated within the parentTemplate / parentStyleSheet.

Another thought -- get rid of stylesheets altogether and just rely on inline <style> tags in templates to reduce the work we're doing on the xcomponent side?

Getting access to parent component information

Thank you for such an amazing library! I can't image all the efforts being put into making this library and sharing it with the community.

  1. I need to access ParentXComponent from ChildXComponent. I can't find a way to access details in the parent such as the parent origin or source. I've tried to use window.parent, event.source but can't seem to make it work.
  2. Is there any way to access parents information after outside the attach callback in the child.

Thanks!

Cookie Detection

Can we make it easier for people to error out if they don't support cookies-disabled mode?

JSON schema for props?

We have plans, at least in PayPal, for some pretty complex objects being passed down as props.

Should be include support for json schema? Maybe this is overkill and could just be done on the child window though...

The lightbox gets displayed for context 'iframe'

Hi,

I expect 'master/demo/basic/iframe.htm' will display inline component.
Actual result: lightbox component gets displayed.

Tested against branch master, on Chrome and Safari.

Please verify.

Thanks,
Ky

Single-track components?

Would it be a good idea to allow single-track components, which have one purpose and a 'success' or 'rejection' state?

I'm imagining something like:

LoginComponent.run().then( ... ).catch( ... );

The idea is the component would tear itself down when it's done with a resolved value. In the login component example, when the user logs in, the component's sole purpose is complete, so it can tear itself down and resolve the promise.

This contrasts to more complex components which can accept an unlimited number of prop based callbacks. These simpler component might be more easy to reason about since invoking them is more of a 'function call'-esque approach.

Sharing error stacks - should we prevent this?

Right now post-robot will share error stacks between windows for function based props that are created on one window and invoked on another.

Wondering if this is a horrible idea from a security perspective, and we should prevent it.

Device detection

Allow component authors to specify which devices/browsers they support.

Support for more frameworks

Need to complete building drivers for:

  • Javascript
  • Script tag
  • Angular
  • React
  • Glimmer
  • Vue
  • Angular 2.0
  • Ember
  • Polymer
  • Backbone
  • Custom HTML element?

Others?

Build url accounting for hash

When I build the url, I should make sure any props are placed before the hash.

For example: if my url is http://foo.bar#baz and I have a prop x=1, the final url should be http://foo.bar?x=1#baz.

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.