Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React Native の WebView でローカルファイルをロードしてJavascriptを実行する

Posted at

ReactNativeで開発していてWebViewを使ってローカルファイルをロードしてJavascriptを実行する必要があって日本語の情報なくてちょっと困ったので備忘録として残しておく
だれかの参考になれば幸いです

※ iOSのみ

概要

  • ロードしたいhtmlやそのhtmlが参照しているcssなどはios/external/ 以下に配置する
  • XCodeにexternalを追加する(ドラッグ&ドロップ)
  • WebViewからはsource={{uri: './index.html'}}でアクセスする

ロードするhtmlを index.html とする
index.htmlの中身

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="main.js"></script>
</head>
<body>
    <div>hoge</div>
    <div class="test"></div>
</body>
</html>

ファイル配置

ReactNativeRootフォルダ
└ios
  └external
    ├index.html
    ├main.css
    └main.js
render() {
    const jsCode = `var testElement = document.getElementByClassName('test')
var appendElement = document.createElement('div')
appendElement.textContent = 'hugu'
testElement.appendChild(appendElement)
`
    return <View>
        <WebView
            source={{uri: './index.html'}}
            injectedJavascript={jsCode}
        />
    </View>
}

参考

6
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Comments

No comments

Let's comment your feelings that are more than good

6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?