React native webview "can't find variable" - webview

I'm making a function using webview in react-native project.
I want to use hello variable to alert when webview is loading,
but I get an error alert
ReferenceError: Can't find variable: hello
I want to use hello variable, I don't want to use "alert("hello")" code;
How do I send hello variable to html??
Here is my code:
import React, { useEffect, useMemo, useState } from 'react';
import { WebView } from 'react-native-webview';
export const WebViewComponent: React.FC<any> = () => {
const hello = 'hello';
const code = `
try {
alert(${hello});
} catch (e) {
alert(e);
}
`;
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<h1>View</h1>
</body>
</html>
`;
return (
<View
style={{
backgroundColor: white,
height: 600,
borderRadius: 20
}}
>
<WebView
javaScriptEnabled={true}
injectedJavaScript={code}
scrollEnabled={true}
bounces={false}
source={{ html }}
/>
</View>
)
}

I want to use injectedJavaScript or injectJavaScript. This code is example.

I solved by changing "${hello}" to ""${hello}"".

Related

Changing the label in the widget to an empty one

I would like to completely remove the label widget so that only the question mark is displayed without any unnecessary spaces.
I tried like this:
label: {
'*': '', //causes the default label from the widget to be displayed
}
Full code that can be pasted in codepen.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, World!</title>
</head>
<body>
<script type="text/javascript">
window.zESettings = {
webWidget: {
launcher: {
label: {
'*': ' ', //spaces changes the default label
}
}
}
};
</script>
<!-- Widget script -->
<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=01f7c129-e3d4-4ed7-ac97-c959acf56f69"> </script>
<!-- End Widget script -->
</body>
</html>
I will be grateful for your help!

React native - webview - load js files

I need to load JS dynamically (depends on user preferences, so cannot hardcoded all in the index.html), but have the problem with that in my app.
Scenario 1 works like a charm:
index.html
<html>
<head>
</head>
<body>
<h1>Highcharts webview demo</h1>
<div id="container" style="width:100%; height:500px;"></div>
<script type="text/javascript" src="library.js"></script>
<script>
library works
</script>
</body>
</html>
app
const webapp2 = require('../web/index.html')
render() {
return <View>
<WebView
source={webapp2}
originWhitelist={'["*"]'}
javaScriptEnabled={true}
domStorageEnabled={true}
scalesPageToFit={true}
scrollEnabled={false}
/>
</View>
}
But when I try to do it by html in source, I have the missing JS library.
Scenario 2 - not working
app
render() {
// Create container for the chart
return <View style={styles.container}>
<WebView
source={{html:`<html><head><script type="text/javascript" src="library.js"></script></head><body><div id="container" style="width:100%; height:500px;"></div><script>Library does not exist yet</script></body></html>`, baseUrl: 'web/'}}
originWhitelist={'["*"]'}
javaScriptEnabled={true}
domStorageEnabled={true}
scalesPageToFit={true}
scrollEnabled={false}
/>
</View>
}
I would like to avoid use external libraries to load js files.
First of load index.html file according to your scenario 1.
Then take a ref of webview component. After webview loads the index.html file, we can inject javascript to load js file like below:
<WebView
ref={ref => (this.webview = ref)}
source={webapp2}
originWhitelist={'["*"]'}
javaScriptEnabled={true}
domStorageEnabled={true}
scalesPageToFit={true}
scrollEnabled={false}
onLoad={() => { this.injectJSFileFromWeb(); }}
/>
you can call this function whenever you want to load js file. but, make sure webview has loaded html.
injectJSFileFromWeb() {
//give the filename according to your need
var jsFileName = "library2.js";
var fp = `
var corescript = document.createElement('script');
corescript.type = 'text/javascript';
corescript.src = "${jsFileName}";
var parent = document.getElementsByTagName('head').item(0);
parent.appendChild(corescript);
void(0);
`;
this.webview.injectJavaScript(fp);
}
Note: checked only on android.

How to get Pixijs with Cocoonjs to use a WebGLRenderer with canvas+ webview engine

I can't seem to get the canvas+ webview engine within Cocoon to use a PIXI.WebGLRenderer no matter what I try. Here is a simple example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<script type="text/javascript" src="http://pixijs.download/release/pixi.js"></script>
<title>Simple Test</title>
</head>
<body style="background-color: #99ff99; margin: 0; padding: 0;" onload="runTest()">
<script>
function runTest() {
var renderer = PIXI.autoDetectRenderer( 500, 200 );
document.body.appendChild( renderer.view );
var stageContainer = new PIXI.Container();
var text = new PIXI.Text( 'renderer.type='+renderer.type, { fontFamily: "Arial", fontSize: '12px', fill: "white" } );
text.x = text.y = 50;
stageContainer.addChild( text );
renderer.render( stageContainer );
}
</script>
</body>
</html>
With the Cocoon Launcher app I've tested this on:
iPhone5 (iOS 10.2)
iPad2 (iOS 9.3.5)
HP 10 Plus (android 4.4.2)
With webview+, all display "renderer=1" (which means PIXI.WebGLRenderer)
But with canvas+, all display "renderer=2" (which means PIXI.CanvasRenderer)
Is it possible to get canvas+ mode to work with WebGL in Pixi.js?
I have also tried forcing the renderer to be WebGL by replacing the autoDetectRenderer line with:
var renderer = new PIXI.WebGLRenderer( 500, 200 );
In this case my Cocoon Launcher on iphone and ipad crashes!
On the android, it just shows a black screen.
I have also tried with Pixi.js v3.0.1 with the same results.
So, is it possible to use WebGL with Cocoon's Canvas+ mode with Pixi.js?
Any help much appreciated, thanks
I managed to get it working, but not with the latest Pixi.js (v4.2.3), only with an old version - v3.0.10.
The key was to add cordova.js and use the document.addEventListener( "deviceready", runTest, false );
Here is some updated code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script type="text/javascript" src="cordova.js"></script>
<script src="js/pixi-3.0.10.js"></script>
<title>Simple Test</title>
</head>
<body style="background-color: #99ff99; margin: 0; padding: 0;">
<script>
function runTest() {
var renderer = new PIXI.WebGLRenderer( 300, 100 );
document.body.appendChild( renderer.view );
var stageContainer = new PIXI.Container();
var text = new PIXI.Text( 'rrr.type='+renderer.type, { fontFamily: "Arial", fontSize: '12px', fill: "white" } );
text.x = text.y = 50;
stageContainer.addChild( text );
renderer.render( stageContainer );
}
document.addEventListener( "deviceready", runTest, false );
</script>
</body>
</html>
This is only a partial answer because it only works with an outdated version of Pixi.js
As for me, I'm abandoning canvas+ for now because what I got working showed poor and erratic results compared with the webview+ mode. Also, as an aside, according to various performance tests I've made, it seems that the old Pixi.js v3.0.10 is dramatically out performing v4.2.3 as well.. so looks like I'll be sticking with that also.

react native webview:when add baseRrl,then just show html string

In order to achieve the WebView display custom font
on rn 0.28:
var html = 'test';
html = `<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style type="text/css">
#font-face {
font-family: "MyFont";
src: url("fonts/fzbys.ttf");
}
body{font-family: "MyFont"; font-size:28px;}
</style>
</head>
<body>`+html+`
</body>
</html>`;
return (
<View style={[{width:this.state.width, alignItems:'center'}, this.props.styles]}>
<WebView
ref={"wv"}
style={{width:this.state.width, height:100}}
source={{html:html, baseUrl:"file:///android_asset/"}}
domStorageEnabled={true}
javaScriptEnabled={true} />
</View>
);
the font file had in android/app/src/main/assets/fonts, then :
run res

How do I dynamically load HTML and insert into my web page with Dart?

How do I dynamically load a snippet of HTML and insert it into my web page? I am using Dart.
Glad you asked! Using Dart for this task isn't much different than JavaScript, except you get typing, code completion, and a slick editing experience.
First, create the snippet.html:
<p>This is the snippet</p>
Next, create the application. Notice the use of XMLHttpRequest to request the snippet. Also, use new Element.html(string) to create a block of HTML from a string.
import 'dart:html';
void main() {
var div = querySelector('#insert-here');
HttpRequest.getString("snippet.html").then((resp) {
div.append(new Element.html(resp));
});
}
Finally, here's the host HTML page:
<!DOCTYPE html>
<html>
<head>
<title>dynamicdiv</title>
</head>
<body>
<h1>dynamicdiv</h1>
<div id="insert-here"></div>
<script type="application/dart" src="dynamicdiv.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
main.dart:
import 'dart:html';
DivElement div = querySelector('div');
main() async {
String template = await HttpRequest.getString("template.html");
div.setInnerHtml(template, treeSanitizer: NodeTreeSanitizer.trusted);
}
template.html:
<h1>Hello world.</h1>
Check my bird... <em>it flies</em> !
<img src="https://www.dartlang.org/logos/dart-bird.svg">
For the full example, that runs out of the box, see:
https://gist.github.com/kasperpeulen/536b021ac1cf397d4e6d
Note that you need 1.12 to get NodeTreeSanitizer.trusted working.
You can try this example.
https://jsfiddle.net/kofwe39d/ (JS compiled from Dart source code.)
web/main.dart
import 'dart:async';
import 'dart:html';
import 'package:virtual_dom/components/component.dart';
import 'package:virtual_dom/features/state.dart';
import 'package:virtual_dom/helpers/h.dart';
import 'package:virtual_dom/helpers/mount.dart';
import 'package:virtual_dom/helpers/styles.dart';
import 'package:virtual_dom/helpers/vhtml.dart';
void main() {
final app = document.getElementById('app')!;
mount(app, _App());
}
class _App extends Component {
#override
Object render() {
final timer = State.get('timer', () => 3);
final setTimer = State.set<int>('timer');
if (timer > 0) {
Timer(Duration(seconds: 1), () {
setTimer(timer - 1);
});
}
final html = timer > 0
? ''
: '''
Hello, <strong>World!</strong>
''';
final style = styles({'padding': '6px'});
return h('div', {
'style': style
}, [
if (timer > 0) '$timer sec',
h('p', 'Your html:'),
vHtml('div', html),
]);
}
}
web/index.html
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example application</title>
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="styles.css">
<script defer src="main.dart.js"></script>
</head>
<body style="height: 100%; font-family: Verdana,sans-serif; font-size:15px; line-height:1.5">
<div id="app" style="height: 100%;"></div>
</body>
</html>

Resources