GithubHelp home page GithubHelp logo

react-iframe's Introduction

React Iframe

Simple React component for including an iframed page.

Youtube in an iframe

The component is fully typescript-supported.

Usage

import Iframe from 'react-iframe'
<Iframe url="https://www.sdrive.app/embed/1ptBQD"
        width="640px"
        height="320px"
        id=""
        className=""
        display="block"
        position="relative"/>

Properties

url (required) - string the iframe url.

all other attributes are optional

src - string if set, overrides url.

scrolling - string not set if if not provided (deprecated in HTML5).

overflow - string default to "hidden".

loading - string (not added to DOM if not provided).

frameBorder - number default to "0" (deprecated in HTML5).

position - string (not added to DOM if not provided).

id - string if set, adds the id parameter with the given value.

className - string if set, adds the class parameter with the given value.

display - string defaults to "block"

height - string (1px > any number above 0, or 1% to 100%)

width - string (1px > any number above 0, or 1% to 100%)

allowFullScreen - if set, applies the allowFullScreen param (deprecated in HTML5). If set, adds allow="fullscreen".

sandbox - add optional sandbox values. For single value, add as string. For multiple values, add as array ({"allow-scripts", "allow-same-origin"}). Valid values are "allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-top-navigation"

allow - add optional allow values ("geolocation microphone camera midi encrypted-media & more")

styles - add any additional styles here. Will (intentionally) override any of the props above. For instance:

<Iframe url="http://www.youtube.com/embed/xDMP3i36naA"
            position="absolute"
            width="100%"
            id="myId"
            className="myClassname"
            height="100%"
            styles={{height: "25px"}}/>

will set the height to 25px even though it was specified as 100% in the props.

A comprehensive overview of the iframe element is available from the MDN web docs.

Development

All source code resides in the src/ folder. The other code paths are generated by the tsc compiler.

When to use

This project provides a convenient TypeScript-enabled wrapper around the native HTML <iframe> tag. You can achieve the same functionality with the native tag. You do not need to use TypeScript in your project to consume this library.

react-iframe's People

Contributors

ados1991 avatar bklynate avatar brightsider avatar chrisbuttery avatar colmbrady avatar davecarlson avatar fer0x avatar fikemox avatar foxmicha avatar gwendolenlynch avatar hamed-farag avatar nagamejun avatar robbestad avatar shoggomo avatar slipperypenguin avatar theel0ja avatar tikotzky 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

react-iframe's Issues

Support the lazy-loading `loading` attribute

https://addyosmani.com/blog/lazy-loading/

The loading attribute can take the values auto,eager,lazy, browsers that support the attribute may implicitly default to auto to determine if they should use eager or lazy based on distance from viewport. The attribute communicates to the browser how important the image/iframe resource is to prioritize loading, potentially delaying it while it's not within a viewing distance from the current viewport.

Allow postMessage communication

It'd be great to be able to make use of HTML's postMessage API to enable cross origin comms between the iFrame and the parent page. Particularly useful for the use of a lot of Payment forms where you need to securely pass some info between your page and the iFrame.

Might require some re-tooling to work with DOM and iFrame loading. Perhaps it could be an option in the onLoad function?

https://javascript.info/cross-window-communication

Function components cannot be given refs

I'm using a ref with the Iframe:

<Iframe ref={this.myiframe} />

This use to work, but after updating some dependencies I'm getting the following error:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `Context.Consumer`.
    in Iframe (created by Context.Consumer)

Some of my dependencies:

    "react": "^16.8.6",
    "react-iframe": "^1.8.0",
    "styled-components": "^4.2.0",

Need to be able to set `sandbox` property to empty string

I have an application using this component which renders a PDF inside an IFRAME. This component seems to set the sandbox property (at least in Chrome) to be wide open:

sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-top-navigation"

I had to remove this component and replace it with a basic HTML <iframe> tag to get the PDF to render so I could set the sandbox attribute to be blank.

Help?

Will not work for me at all ( does this work with typescript? )

In VS Code if I hover over the import statement I get this test in a popup:

Could not find a declaration file for module 'react-iframe'. 'c:/cloudguest/src/client-admin/react-material.eval/node_modules/react-iframe/index.min.js' implicitly has an 'any' type.
Try npm install @types/react-iframe if it exists or add a new declaration (.d.ts) file containing declare module 'react-iframe';ts(7016)

When I run I get an error:

Check your code at App.js:43.
in Route (at App.js:43)
in Switch (at App.js:40)
in div (at App.js:34)
in App (at src/index.js:9)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:8)
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
index.js:1452

Here is how I am trying to use it:

import { Iframe } from 'react-iframe';

<Route path="/api-docs-swagger" render={props => <Iframe url='/api-docs-swagger' />} />

Render HTML file from src

Hi, when I try to render Iframe with HTML file in src director, it's renders iframe tag with my whole application.
it doesn't matter how I provide the path - src={'./test.html'} works exactly the same.
External links like url="http://www.youtube.com/embed/xDMP3i36naA" works fine

<Iframe src={'src/components/Iframe/test.html'} width="450px" height="450px" id="myId" className="myClassname" display="initial" position="relative"/>

Issue serving built CRA app with <Iframe src="./public/myfile.html">

Hey there, I'm just leaving this in case other people are running into the issue I was.

I was building a CRA app and trying to serve an html file in the /public dir like so

<Iframe url={"./public/myfile.html"} position="absolute" width="100%" height="100%" />

this worked fine when I was running create-react-app locally, but when I tried to serve the build with serve -s ./build I got a weird error where it was serving the original index.html inside of the iframe instead of myfile.html

After some digging I realized that I needed to drop the -s option!

-s, --single                        Rewrite all not-found requests to index.html

this worked just fine:

serve ./build

Cheers!

I can't set style

when I set style={{color: '#ddd'}} it can't work
<Iframe url={day.desc_url} width="100%" height="600px" style={{color: '#ddd'}} position="relative" allowFullScreen/>

"styles" is not handled properly

Reproduce:

ReactDOM.render(
  <Iframe url='https://www.test-cors.org/'
                  width='100%'
                  height='100%'
                  styles={{ borderWidth: '0' }}
                  position='relative'/>,
  root
)

The result is an iframe with no "border-width" set, with an extra attribute styles="[object Object]"

Cross domain page height cannot be natively set

From what I can tell, the tool doesn't currently address page heights across different domains without specifically spelling it out in pixels manually (setting height="100%" doesn't work for cross-domain iframes). Are there any plans to address this? Thank you

What's going on with the update/release commits?

Looking over the commit history to see what had changed since earlier this year. The CHANGELOG.md(or releases page) isn't too useful since commit messages adding changes often either don't use the keywords it expects at all or uses them incorrectly(part of a chore for release).

You have a pattern of release commits sometimes 2-3 times in a row. Usually only the first may contain actual changes or be for a prior commit. The others just seem to be version bumps for no reason? Is this a bug with some release automation?

Allow scroll bar to be removed

It would be very useful if there was an option to remove the scrollbar. Currently it is possible to hide overflow using the styles attribute, but there is a confusing scrollbar left behind. It shouldn't be too much work to get this working, just accept one more prop.

IE11 support

It looks like when trying to use this component in IE11 it throws errors for "SCRIPT438: Object doesn't support property or method 'assign' " which tracking down the issue means that it doesn't like Object.assign()

I found a workaround if you want to try it (if you really want to support IE11) to use the object-assign package here: https://github.com/sindresorhus/object-assign instead of the native Object.assign()

Allow for setting title or aria-label for accessibility reasons

We have a requirement which has been exposed by the "axe" developer tool which shows that we have an issue with the iframe not including a title or label:

Issue description
Ensures <iframe> and elements contain a non-empty title attribute

Impact: serious
Element location
iframe
Element source
<iframe frameborder="0" src="<snip>" target="_parent" allowfullscreen="" height="100%" name="" width="100%" style="position: absolute; display: block; height: 100%; width: 100%;"></iframe>
To solve this violation, you need to:
Fix at least one (1) of these issues:

  • aria-label attribute does not exist or is empty
  • aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty
  • Element has no title attribute or the title attribute is empty
  • Element's default semantics were not overridden with role="presentation"
  • Element's default semantics were not overridden with role="none"

Would be good if, in the simplest case, an optional "title" attribute could be passed through into the HTML.

What's the difference with just using `<iframe ... />`?

I'm trying to understand why anyone would use this library, where they can simply use a plain <iframe />.

What does this library do, apart from wrapping the iframe in a PureComponent, and limiting support to only the defined properties?

How to set styles to component?

I am trying to set

<IFrame style={{position: 'fixed', width: '100%', height: '100%', left: 0}} url={...}  />

But its not applying

Create-react-app: UglifyJS build failing for latest releases

Related: #25

With latest releases, when running npm run build for a CRA app it fails due to UglifyJS not supporting ES6 AFAICT. Working fine with (at least) version 1.1.0.

Error log:

> [email protected] build /home/rof/src/github.com/HealthTree/healthtree-app
> react-scripts build

Creating an optimized production build...
Skipping static resource "/home/rof/src/github.com/HealthTree/healthtree-app/build/static/js/main.6557b736.js" (14.9 MB) - max size is 2.1 MB
Failed to compile.

static/js/main.6557b736.js from UglifyJs
Unexpected token: punc (,) [./~/react-iframe/dist/es/iframe.js:5,0][static/js/main.6557b736.js:166721,4]

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `react-scripts build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/rof/.npm/_logs/2019-04-14T05_01_49_340Z-debug.log

onLoad properties on Component

In the native iframe we have something like this:

<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe> We may want to include that to the module.

React Optimized Build Failed to Minify

With the release today get this error when creating an optimized build:

Failed to minify the code from this file:

    ../node_modules/react-iframe/index.js:5

Error in Firefox

Using react-iframe is throwing an error in Firefox:

Browser Error: SyntaxError: class is a reserved identifier
Takes me to this line :

const Iframe = class extends __WEBPACK_IMPORTED_MODULE_0_react__["PureComponent"] {
  render() {

iframe breaks back button

Rendering the react-iframe adds to the history therefore breaks the back button. Is there anyway to not add to the history when switching between iframes?

README example vs typescript

Hello! Thanks for creating this library :)
Just wanted to note that display="initial" is part of the example in the README but in node_modules/react-iframe/types.d.ts, typescript will complain that the display attribute can only have "block" | "none" | "inline".

Cannot Use in IE11

It appears that the exported index.js does not supported IE11 usage, primarily from the class declaration on line 5. Unfortunately, IE11 does not support ES6 classes: https://caniuse.com/#feat=es6-class

I've attempted replacing the index.js with code from the index.min.js and found that it works as intended. Would it be possible to change the deployed package to have an index.js that is the babelified / minified version and not the pure ES6 one?

"Unrecognized origin" warnings?

I get these warnings when running my Iframe component with the corresponding 'allow' variables set.

Unrecognized origin: 'microphone'.
Unrecognized origin: 'camera'.
Unrecognized origin: 'midi'.

This is the iFrame generating the warnings:

<Iframe
  url={pageUrl}
  width="100%"
  height="100%"
  id={'iframe__' + props.id}
  display="absolute"
  position="relative"
  frameBorder="0"
  allow="microphone camera midi"
/>

Trying to render an HTML file inside the Frame component

Hey,

I have tried this component and it works very well with YouTube links but I am trying to embed an HTML file that contains animation inside React using this component but it doesn't work as expected. Does anyone have any recommendations to overcome it?

Howto set id or className?

In my component, trying

  <Iframe
    allowFullScreen
    className="editor-frame"
    id="editor-frame"
    height="100%"
    position="relative"
    url={url}
    width="100%"
  />

does not work

react iframe displays blank page with base64 pdf data with IE 15 windows 10

React iframe displays blank page with base64 pdf data with IE 15 windows 10. I tested it with browserstack. If I supply a real pdf file, it will work in IE.

Here is my test project.
https://github.com/kenpeter/test_popup_iframe

Main code like this:

function App() {
  const meta = 'data:application/pdf;base64,';

  const data = meta +  
    'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
    'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
    'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
    'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
    'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
    'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
    'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
    'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
    'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
    'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
    'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
    'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
    'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G';

  return (
    <div className="App">
      <Iframe src={data}
        width="450px"
        height="450px"
        id="myId"
        className="myClassname"
        display="initial"
        position="relative"/>
    </div>
  );
}

Element ref was specified as a string (iframe) but no owner was set

I get this error when putting the example iframe into my web app (created using CRA):

Element ref was specified as a string (iframe) but no owner was set. This could happen for one of the following reasons:
1. You may be adding a ref to a functional component
2. You may be adding a ref to a component that was not created inside a component's render method
3. You have multiple copies of React loaded
See https://fb.me/react-refs-must-have-owner for more information.

Code:

class DashboardView extends React.Component{
	render() {
		return(
			<div>
				<header className="App-header">
              		<h1 className="App-title">Welcome to my app</h1>
            	</header>
            	<p className="App-intro">
              		Go to <Link to="/something">Entity Curation</Link> to do stuff.
            	</p>
				<Iframe url="http://www.youtube.com/embed/xDMP3i36naA"
        width="450px"
        height="450px"
        id="myId"
        className="myClassname"
        display="initial"
        position="relative"
        allowFullScreen/>
      		</div>
		);
	}
}

Missing dependencies in package.json

Im using JSPM to package your module but it has problems doing so because package.json does not declare 'prop-types' or 'object-assign' as either dependencies or peerDependencies. This results in a runtime error loading your module because JSPM cant include undeclared dependencies without some extra JSPM override config.

Would you consider accepting a P.R to correct this?

Package needs to implement Google's new "allow" attribute

Google has recently deprecated permissions for access to user devices in cross-origin iframes. Please review this article: https://dev.chromium.org/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes#TOC-To-continue-to-use-permissions-from-iframes-on-your-website...

I have attempted to fork the project and add the attribute myself, compile it, and then reinstall the package from my GitHub instead of from NPM. But when I try to load it into an application I am working on and compile the app, it throws 50 errors to the browser console, like the code has not been transpiled. The only way I can get this package to work is to use the official one from NPM (which doesn't include "allow").

I can hack around this for this app (its a class project). But for future, would probably be a good idea to implement this attribute, if only for cross-browser support.

Import error

Importing react-iframe produces an error

Examples:
Testing on
https://runkit.com/npm/react-iframe

Produces two syntax errors:
SyntaxError: Unexpected token import
A stack trace for this error could not be retrieved because stack was already called.


Importing locally and attempting to run a file with the import using either

var Iframe =  require('react-iframe');
import Iframe from 'react-iframe';

produces the following error:

index.js:1 Uncaught SyntaxError: Unexpected token import

Support for Mobile Devices?

Hello, I am using your npm module to render youtube videos. Specifically when a user clicks on an image, a Bootstrap modal will pop up and play the youtube video, which is a form of lazy loading. Everything works great desktop wise.

This would be an image:
image

This would be the modal element activated and using your module to render the corresponding music video:
image

However, the modal element is empty on a mobile device, meaning that the iframe component is not rendered. I was on my iphone using Safari, I'm not sure if it's a compatibility issue. Is there support for mobile devices at all (which would be necessary since everyone shifting away from desktop to mobile)

Thanks for any clarification!
*Side note as well: for some reason, allowFullScreen attribute does not seem to be working. I tried allowFullScreen on its own as a way of setting it, and allowFullScreen={"true"} as another way of setting it with JSX syntax

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.