Search code examples
javascriptwebviewuiwebviewreact-native

Inject dynamic vars into React Native's WebView's injectedJavaScript string


I'm loading this WebView in my app:

           <WebView
                style={{
                    marginTop: 5,
                    flex:1,
                    flexDirection: 'column',
                    alignItems:'center',
                    justifyContent: 'center',
                    backgroundColor: 'rgba(255,255,255,0.8)',
                    height:300
                  }}
                source={require('./test.html')}
                injectedJavaScript={injectedScript}
                scalesPageToFit={true}
            />

Since I want this html file to display a string that I got just before the render was called - I want to do the following:

        let injectedScript = `CKEDITOR.instances.editor.setData(${bodyForDisplay});`;

But it just doesn't work. When I replace the ${bodyForDisplay} with a static string (i.e "test") - it works flawlessly.

Any ideas on how to inject a dynamic value here?


Solution

  • You need to surround ${bodyForDisplay} with a single or double quotes, as it's a string parameter to the method setData.

    Also, make sure to escape the string inside bodyForDisplay so it won't close the opening string quote (single or double). It's never safe to trust user input so you should properly escape other chars in that string as well.