Skip to content
This repository has been archived by the owner on Jan 19, 2023. It is now read-only.

Commit

Permalink
fix: avoid cross-origin errors from using window.top
Browse files Browse the repository at this point in the history
  • Loading branch information
fritz-c committed Mar 9, 2018
1 parent b08be00 commit 5bb5ac9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/react-image-lightbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getWindowWidth,
getWindowHeight,
getIEVersion,
getHighestSafeWindowContext,
} from './util';
import {
KEYS,
Expand Down Expand Up @@ -157,10 +158,6 @@ class ReactImageLightbox extends Component {
}

componentWillMount() {
//PB: this is so users don't get the following error if this is in an iFrame
//Uncaught DOMException: Blocked a frame with origin "my-child-site.com" from accessing a cross-origin frame.

this.windowContext = (global.window.top == global.window.self) ? global.window.top : global.window.self;
// Timeouts - always clear it before umount
this.timeouts = [];

Expand Down Expand Up @@ -226,6 +223,9 @@ class ReactImageLightbox extends Component {
componentDidMount() {
ReactImageLightbox.loadStyles();

// Prevents cross-origin errors when using a cross-origin iframe
this.windowContext = getHighestSafeWindowContext();

this.listeners = {
resize: this.handleWindowResize,
mouseup: this.handleMouseUp,
Expand All @@ -237,7 +237,6 @@ class ReactImageLightbox extends Component {
pointercancel: this.handlePointerEvent,
};
Object.keys(this.listeners).forEach(type => {

this.windowContext.addEventListener(type, this.listeners[type]);
});

Expand Down
21 changes: 21 additions & 0 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,24 @@ export function getWindowWidth() {
export function getWindowHeight() {
return typeof global.window !== 'undefined' ? global.window.innerHeight : 0;
}

// Get the highest window context that isn't cross-origin
// (When in an iframe)
export function getHighestSafeWindowContext(self = global.window.self) {
// If we reached the top level, return self
if (self === global.window.top) {
return self;
}

const getOrigin = href => href.match(/(.*\/\/.*?)(\/|$)/)[1];

// If parent is the same origin, we can move up one context
// Reference: https://stackoverflow.com/a/21965342/1601953
if (getOrigin(self.location.href) === getOrigin(self.document.referrer)) {
return getHighestSafeWindowContext(self.parent);
}

// If a different origin, we consider the current level
// as the top reachable one
return self;
}

0 comments on commit 5bb5ac9

Please sign in to comment.