Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Created October 18, 2017 21:25
Show Gist options
  • Save loretoparisi/a5cd7ab92d221578cc540f530a777b56 to your computer and use it in GitHub Desktop.
Save loretoparisi/a5cd7ab92d221578cc540f530a777b56 to your computer and use it in GitHub Desktop.
React Code Injection
injc=(src,cbk) => { let script = document.createElement('script');script.src = src;document.getElementsByTagName('head')[0].appendChild(script);script.onload=()=>cbk() }
injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js",() => injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js",() => console.log("ready")))
@loretoparisi
Copy link
Author

The class ReactInjected will fire a click event on a button of a existing page after the React library has been injected into that page.

let injc=(src,cbk) => { let script = document.createElement('script');script.src = src;document.getElementsByTagName('head')[0].appendChild(script);script.onload=()=>cbk() }
injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js",() => injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js",() => {

class ReactInjected extends React.Component{
  simulateClick(e) {
    e.click()
  }
  render(){
    return <div className="UFIInputContainer"
    ref={this.simulateClick} onClick={()=> console.log('click injection')}>
      hello
      </div>
  }
}
ReactDOM.render(<ReactInjected/>, document.getElementById('app'))

} ))

@loretoparisi
Copy link
Author

loretoparisi commented Jun 8, 2018

Injector function definition:

let injc=(src,cbk) => { let script = document.createElement('script');script.src = src;document.getElementsByTagName('head')[0].appendChild(script);script.onload=()=>cbk() }

React lib code injection:

injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js",() => injc("https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js",() => { console.log("Hello React")}))

@loretoparisi
Copy link
Author

To make it working it's important to use the React and ReactDom development build:

let injc=(src,cbk) => { let script = document.createElement('script');script.src = src;document.getElementsByTagName('head')[0].appendChild(script);script.onload=()=>cbk() }
injc("https://unpkg.com/react@16/umd/react.development.js",() => injc("https://unpkg.com/react-dom@16/umd/react-dom.development.js",() => { console.log("Hello")}))
ReactDOM.render('<Hello name="World" />', document.getElementById('container'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment