• Stars
    star
    3,072
  • Rank 14,658 (Top 0.3 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A pure JavaScript CORS alternative

XDomain

Summary

A pure JavaScript CORS alternative. No server configuration required - just add a proxy.html on the domain you wish to communicate with. This library utilizes XHook to hook all XHR, so XDomain will work seamlessly with any library.

Features

  • Simple
  • Library Agnostic
    • With jQuery $.ajax (and subsequently $.get, $.post)
    • With Angular $http service
  • Cross domain XHR just magically works
  • Easy XHR access to file servers:
  • Includes XHook and its features
  • proxy.html files (slaves) may:
    • White-list domains
    • White-list paths using regular expressions (e.g. only allow API calls: /^\/api/)
  • Highly performant
  • Seamless integration with FormData
  • Supports RequiresJS and Browserify

Download

Live Demos

Browser Support

All except IE6/7 as they don't have postMessage

Quick Usage

Note: It's important to include XDomain before any other library. When XDomain loads, XHook replaces the current window.XMLHttpRequest. So if another library saves a reference to the original window.XMLHttpRequest and uses that, XHook won't be able to intercept those requests.

  1. On your slave domain (http://xyz.example.com), create a small proxy.html file:

    <!DOCTYPE HTML>
    <script src="//unpkg.com/[email protected]/dist/xdomain.min.js" master="http://abc.example.com"></script>
  2. Then, on your master domain (http://abc.example.com), point to your new proxy.html:

    <script src="//unpkg.com/[email protected]/dist/xdomain.min.js" slave="http://xyz.example.com/proxy.html"></script>
  3. And that's it! Now, on your master domain, any XHR to http://xyz.example.com will automagically work:

    //do some vanilla XHR
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://xyz.example.com/secret/file.txt");
    xhr.onreadystatechange = function(e) {
      if (xhr.readyState === 4) console.log("got result: ", xhr.responseText);
    };
    xhr.send();
    
    //or if we are using jQuery...
    $.get("http://xyz.example.com/secret/file.txt").done(function(data) {
      console.log("got result: ", data);
    });

Tip: If you enjoy being standards compliant, you can also use data-master and data-slave attributes.

Using multiple masters and slaves

The following two snippets are equivalent:

<script src="//unpkg.com/[email protected]/dist/xdomain.min.js" master="http://abc.example.com/api/*"></script>
<script src="//unpkg.com/[email protected]/dist/xdomain.min.js"></script>
<script>
xdomain.masters({
  'http://abc.example.com': '/api/*'
});
</script>

So, we can then add more masters or (slaves) by simply including them in the object, see API below.

API

xdomain.slaves(slaves)

Will initialize as a master

Each of the slaves must be defined as: origin: proxy file

The slaves object is used as a list slaves to force one proxy file per origin.

The Quick Usage step 2 above is equivalent to:

<script src="//unpkg.com/[email protected]/dist/xdomain.min.js"></script>
<script>
  xdomain.slaves({
    "http://xyz.example.com": "/proxy.html"
  });
</script>

xdomain.masters(masters)

Will initialize as a slave

Each of the masters must be defined as: origin: path

origin and path are converted to a regular expression by escaping all non-alphanumeric chars, then converting * into .* and finally wrapping it with ^ and $. path can also be a RegExp literal.

Requests that do not match both the origin and the path regular expressions will be blocked.

So you could use the following proxy.html to allow all subdomains of example.com:

<script src="/dist/xdomain.min.js" data-master="http://*.example.com/api/*.json"></script>

Which is equivalent to:

<script src="/dist/xdomain.min.js"></script>
<script>
  xdomain.masters({
    "http://*.example.com": "/api/*.json"
  });
</script>

Where "/api/*.json" becomes the RegExp /^\/api\/.*\.json$/

Therefore, you could allow ALL domains with the following proxy.html:

<!-- BEWARE: VERY INSECURE -->
<script src="/dist/xdomain.min.js" master="*"></script>

xdomain.debug = false

When true, XDomain will log actions to console

xdomain.timeout = 15e3ms (15 seconds)

Number of milliseconds until XDomains gives up waiting for an iframe to respond

xdomain.on(event, handler)

event may be log, warn or timeout. When listening for log and warn events, handler with contain the message as the first parameter. The timeout event fires when an iframe exeeds the xdomain.timeout time limit.

xdomain.cookies

WARNING ⚠️ Chrome and possibly other browsers appear to be blocking access to the iframe's document.cookie property. This means Slave-Cookies are no longer supported in some browsers.

When withCredentials is set to true for a given request, the cookies of the master and slave are sent to the server using these names. If one is set to null, it will not be sent.

//defaults
xdomain.cookies = {
  master: "Master-Cookie"
  slave: "Slave-Cookie"
};

Note, if you use "Cookie" as your cookie name, it will be removed by browsers with Disable 3rd Party Cookies switched on - this includes all Safari users and many others who purposefully enable it.

Conceptual Overview

  1. XDomain will create an iframe on the master to the slave's proxy.
  2. Master will communicate to slave iframe using postMessage.
  3. Slave will create XHRs on behalf of master then return the results.

XHR interception is done seamlessly via XHook.

Internet Explorer

Use the HTML5 document type <!DOCTYPE HTML> to prevent your page from going into quirks mode. If you don't do this, XDomain will warn you about the missing JSON and/or postMessage globals and will exit.

If you need a CORS Polyfill and you're here because of IE, give this XHook CORS polyfill a try, however, be mindful of the restrictions listed below.

FAQ / Troubleshooting

Q: But I love CORS

A: You shouldn't. You should use XDomain because:

  • IE uses a different API (XDomainRequest) for CORS, XDomain normalizes this silliness. XDomainRequest also has many restrictions:

    • Requests must be GET or POST
    • Requests must use the same protocol as the page http -> http
    • Requests only emit progress,timeout and error
    • Requests may only use the Content-Type header
  • The CORS spec is not as simple as it seems, XDomain allows you to use plain XHR instead.

  • On a RESTful JSON API server, CORS will generate superfluous traffic by sending a preflight OPTIONS request preceding various types of requests.

  • Not everyone is able to modify HTTP headers on the server, but most can upload a proxy.html file.

  • Google also uses iframes as postMessage proxies instead of CORS in its Google API JS SDK:

    <iframe name="oauth2relay564752183" id="oauth2relay564752183"
    src="https://accounts.google.com/o/oauth2/postmessageRelay?..."> </iframe>

Q: XDomain is interfering with another library!

A: XDomain attempts to perfectly implement XMLHttpRequest2 so there should be no differences. If there is a difference, create an issue. Note however, one purposeful difference affects some libraries under IE. Many use the presence of 'withCredentials' in new XMLHttpRequest() to determine if the browser supports CORS.

The most notable library that does this is jQuery, so XHook purposefully defines withCredentials to trick jQuery into thinking the browser supports CORS, thereby allowing XDomain to function seamlessly in IE. However, this fix is detrimental to other libraries like: MixPanel, FB SDK, Intercom as they will incorrectly attempt CORS on domains which don't have a proxy.html. So, if you are using any of these libraries which implement their own CORS workarounds, you can do the following to manually disable defining withCredentials and manually reenable CORS on jQuery:

//fix trackers
xhook.addWithCredentials = false;
//fix jquery cors
jQuery.support.cors = true;

Note: In newer browsers xhook.addWithCredentials has no effect as they already support withCredentials.

Q: XDomain works for a few requests and then it stops.

A: Most likely, the slave iframe was removed - this is often due to libraries like Turbolinks

Q: In IE, I'm getting an Access Denied error

A: This is error occurs when IE attempts a CORS request. Read on.

Q: The browser is still sending CORS requests.

A: Double check your slaves configuration against the examples. If your slaves configuration is correct, double-check that you're including XDomain before window.XMLHttpRequest is referenced anywhere. The safest way to fix it is to include XDomain first, it has no dependencies, it only modifies window.XMLHttpRequest.

Q: The script is loads but the 'Quick Start' steps don't work

A: XDomain only searches the script tags for master and slave attributes if they have xdomain in the src. So, if you've renamed or embedded XDomain, you'll need to use the API in order to insert your masters and slaves.

Q: It's still not working!

A: Enable xdomain.debug = true; (or add a debug="true" attribute to the script tag) on both the master and the slave and copy the console.logs to a new issue. If possible, please provide a live example demonstrating your issue.

Change log

  • 0.8.2

    • Removed CoffeeScript
    • Restructured with ES6 and Common.js
    • Use parcel as bundler

Todo

  • Saucelabs testing is broken, need to swap to BrowserStack.

Contributing

  • npm install
  • Tab 1
    • npm run dev
  • Tab 2
    • npm i -g serve
    • serve -p 3000 .
    • open http://localhost:3000/example/local
  • npm run build
  • See dist/

Donate

BTC 1AxEWoz121JSC3rV8e9MkaN9GAc5Jxvs4

MIT License

Copyright © 2016 Jaime Pillora <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Analytics

More Repositories

1

chisel

A fast TCP/UDP tunnel over HTTP
Go
12,490
star
2

cloud-torrent

☁️ Cloud Torrent: a self-hosted remote torrent client
Go
5,744
star
3

overseer

Monitorable, gracefully restarting, self-upgrading binaries in Go (golang)
Go
2,276
star
4

notifyjs

Notify.js - A simple, versatile notification library
1,903
star
5

xhook

Easily intercept and modify XHR request and response
HTML
983
star
6

webproc

Wrap any program in a simple web-based user-interface
Go
725
star
7

docker-dnsmasq

dnsmasq in a docker container, configurable via a simple web UI
Dockerfile
723
star
8

go-tcp-proxy

A small TCP proxy written in Go
Go
694
star
9

backoff

Simple backoff algorithm in Go (golang)
Go
627
star
10

jquery.rest

A jQuery plugin for easy consumption of RESTful APIs
CoffeeScript
614
star
11

ipfilter

A package for IP Filtering in Go (golang)
Go
386
star
12

node-edit-google-spreadsheet

A simple API for editing Google Spreadsheets
JavaScript
304
star
13

base64-encoder

Base64 Encoder
HTML
260
star
14

installer

One-liner for installing binaries from Github releases
Go
200
star
15

node-torrent-cloud

Torrent Cloud – A self-hosted Bittorrent client in the Cloud
JavaScript
183
star
16

velox

Real-time Go struct to JS object synchronisation over SSE and WebSockets
Go
180
star
17

grunt-aws

A Grunt interface into the Amazon Node.JS SDK
JavaScript
174
star
18

opts

A Go (golang) package for building frictionless command-line interfaces
Go
162
star
19

verifyjs

Verify.js - A powerful, customizable asynchronous validation library
JavaScript
159
star
20

ssh-tron

Multiplayer Tron over SSH, written in Go
Go
143
star
21

go-ogle-analytics

Monitor your Go (golang) servers with Google Analytics
HTML
133
star
22

cloud-gox

A Go (golang) Cross-Compiler in the cloud
Go
132
star
23

media-sort

Automatically organise your movies and tv series
Go
118
star
24

go-tld

TLD Parser in Go
Go
114
star
25

node-load-tester

Simple load testing with Node.js
JavaScript
88
star
26

sshd-lite

A feature-light sshd(8) for Windows, Mac, and Linux written in Go
Go
85
star
27

csv-to-influxdb

Import CSV files into InfluxDB
Go
81
star
28

node-logbook

A simple, unobtrusive logger for Node
JavaScript
61
star
29

spy

Spy - Watches for file changes, restarts stuff
Go
61
star
30

go-and-ssh

Go and the Secure Shell protocol
Go
58
star
31

node-glob-all

Provide multiple patterns to node-glob
JavaScript
57
star
32

serve

Your personal HTTP file server in Go
Go
53
star
33

go-sandbox

An alternate frontend to the Go Playground
JavaScript
52
star
34

scraper

A dual interface Go module for building simple web scrapers
Go
50
star
35

node-google-sheets

Google Sheets v4 API using Node.js
JavaScript
44
star
36

dedup

A cross platform command-line tool to deduplicate files, fast
Go
42
star
37

archive

Archiver is a high-level API over Go's archive/tar,zip
Go
33
star
38

icmpscan

ICMP scan all hosts across a given subnet in Go (golang)
Go
29
star
39

hashedpassword

A small Go (Golang) package for hashed passwords
Go
26
star
40

gswg-examples

Getting Started with Grunt - Code Examples
JavaScript
25
star
41

webfont-downloader

A small web service which converts webfonts into zip archives
Go
24
star
42

aoc-in-go

A template repository for rapidly writing Advent of Code solutions in Go
Go
21
star
43

conncrypt

Symmetrically encrypt your Go net.Conns
Go
19
star
44

s3hook

Transparent Client-side S3 Request Signing
JavaScript
19
star
45

grunt-source

Reuse a Grunt environment across multiple projects
JavaScript
18
star
46

docker-cloud-torrent-openvpn

cloud-torrent and OpenVPN in a docker container
Shell
17
star
47

longestcommon

Longest common prefix/suffix across of list of strings in Go (Golang)
Go
16
star
48

mega-stream

Stream media content from Mega
JavaScript
14
star
49

node-gitlab-deploy

Deploy a Node server via a Gitlab Webhook
JavaScript
13
star
50

go-template

An automatic cross-compiling Go (golang) repository template using goreleaser and Github actions
Shell
13
star
51

ansi

Easy to use ANSI control codes
Go
12
star
52

subfwd

URL shortening via sub-domains, written in Go
HTML
12
star
53

js-play

A JavaScript playground/sandbox for learning, testing and prototyping
CSS
12
star
54

upnpctl

A small UPnP client
Go
11
star
55

go-echo-server

View your requests in JSON format
Go
10
star
56

node-echo-server

Responds with the JSONified Request
JavaScript
10
star
57

ddns-daemon

A Simple Dynamic DNS Daemon using Node.js and Route53
JavaScript
10
star
58

whos-home

ARP scan your subnet and POST findings
Go
10
star
59

uploader

A small server to receive files over HTTP
JavaScript
9
star
60

dynflare

DynamicDNS using Cloudflare
Go
9
star
61

pnode

peer-to-peer dnode over anything!
JavaScript
9
star
62

go433

Send and receive 433 MHz using a RaspberryPi and Go
Go
9
star
63

sockfwd

Forward a unix socket to a tcp socket
Go
9
star
64

vip

An IPv4 addressing Go (golang) module, based on uint32 instead of []byte
Go
8
star
65

ipflare

Find your public IP address according to Cloudflare
Go
8
star
66

node-ssh-http-agent

An HTTP agent for tunnelling through SSH connections
JavaScript
7
star
67

eventsource

An eventsource event encoder in Go (golang)
Go
7
star
68

sizestr

Pretty print byte counts in Go
Go
7
star
69

docker-caddy

Caddy in a docker container, configurable via a simple web UI
Dockerfile
7
star
70

sleep-on-lan

Send your computer to sleep via HTTP
JavaScript
7
star
71

requestlog

Simple request logging in Go (golang)
Go
6
star
72

pnode-store

A synchronized data store between connected Node.js applications
JavaScript
6
star
73

castlebot

🏰 A bot for your castle
Go
5
star
74

docker-vpn

Dockerized SoftEther VPN with a Web GUI
Shell
5
star
75

node-imdb-sort

Sort files based on IMDB data
CoffeeScript
5
star
76

jquery.prompt

Styled text prompts any element
CoffeeScript
5
star
77

gswg-io

Getting Started with Grunt - Homepage
HTML
5
star
78

compilejs

A mini Grunt.js for the browser
CoffeeScript
5
star
79

go-realtime

Keep your Go structs in sync with your JS objects
JavaScript
4
star
80

md-tmpl

Simple markdown templating using shell commands
Go
4
star
81

cookieauth

Cookie-based Basic-Authentication HTTP middleware for Go (golang)
Go
4
star
82

maplock

A map of locks in Go
Go
4
star
83

opts-examples

A Go (golang) package for building frictionless command-line interfaces
Go
4
star
84

go-mime

Extends pkg/mime with embedded mime types
Go
4
star
85

tranquil

Generate powerful RESTful JSON APIs
CoffeeScript
3
star
86

ipmath

IP Address Math in Go (golang)
Go
3
star
87

xtls

TLS utils
Go
3
star
88

puzzler

A programming puzzle framework in Go
Go
3
star
89

goff

Concatenate audio files, built with Go and FFmpeg
Go
3
star
90

prettyprinter

Simple Pretty Printer using Google's Prettify
HTML
3
star
91

github-badge-maker

Github Badge Maker
JavaScript
3
star
92

opts-talk

A talk on opts, for the Sydney Go Meetup
Go
3
star
93

grunt-source-web

A Grunt Source project to build optimized static websites
CoffeeScript
3
star
94

playground

Next version of https://js.jpillora.com
2
star
95

node-king

The king of your nodes - A powerful command and control center for your server infrastructure
JavaScript
2
star
96

bookshelf

Your personal bookshelf
HTML
2
star
97

debator-lander

Interactive and transparent debates online
2
star
98

webscan

Scans the entire Web for particular server types and devices
2
star
99

xmlfmt

A pure Go streaming XML formatter
Go
2
star
100

vigilant

Simple CLI tool for running multiple CLI tools in the same process
JavaScript
2
star