Files: 6f207214603cecdfaceac26619937078ba1e2a1b / BeakerWebView.js
1574 bytesRaw
1 | import React, { Component } from 'react'; |
2 | import { WebView } from 'react-native'; |
3 | |
4 | const BASE_URI = 'http://localhost'; |
5 | |
6 | class BeakerWebView extends Component { |
7 | constructor (props) { |
8 | super(props); |
9 | |
10 | this.getResourcesBaseScript = this.getResourcesBaseScript.bind(this); |
11 | } |
12 | |
13 | state = { |
14 | navigatingUri: '' |
15 | } |
16 | |
17 | UNSAFE_componentWillReceiveProps (nextProps) { |
18 | let { uri, port } = nextProps; |
19 | |
20 | // Verify protocol |
21 | const datExpression = new RegExp(/^dat:\/\/?/i); |
22 | |
23 | if (datExpression.test(uri)) { |
24 | uri = uri.replace(datExpression, ''); |
25 | } |
26 | |
27 | const finalUri = `${BASE_URI}:${port}/${uri}`; |
28 | |
29 | return this.setState({ |
30 | navigatingUri: finalUri |
31 | }); |
32 | } |
33 | |
34 | getResourcesBaseScript () { |
35 | const { port } = this.props; |
36 | const { navigatingUri } = this.state; |
37 | |
38 | return `(function () { |
39 | var assets = Array.from(document.querySelectorAll('[href]')).concat(Array.from(document.querySelectorAll('[src]'))); |
40 | |
41 | for (var index = 0; index < assets.length; index++) { |
42 | var element = assets[index]; |
43 | var attr = element.href ? 'href' : 'src'; |
44 | var elementSrc = element[attr].replace('${BASE_URI}:${port}', '${navigatingUri}'); |
45 | |
46 | element[attr] = elementSrc; |
47 | } |
48 | }());`; |
49 | } |
50 | |
51 | render () { |
52 | const { navigatingUri } = this.state; |
53 | const injectedJavaScript = this.getResourcesBaseScript(); |
54 | |
55 | return ( |
56 | <WebView source={{ uri: navigatingUri }} |
57 | automaticallyAdjustContentInsets={ true } |
58 | injectedJavaScript={ injectedJavaScript } /> |
59 | ); |
60 | } |
61 | } |
62 | |
63 | export default BeakerWebView; |
Built with git-ssb-web