React Native auto height WebView doesn't work on android - webview

I'm implementing a WebView with dynamic height. I found the solution that works like a charm on iOS and doesn't work on android. The solution uses JS inside the WV to set the title to the value of the content height. Here's the code:
...
this.state = {webViewHeight: 0};
...
<WebView
source={{html: this.wrapWevViewHtml(this.state.content)}}
style={{width: Dimensions.get('window').width - 20, height: this.state.webViewHeight}}
scrollEnabled={false}
javaScriptEnabled={true}
injectedJavaScript="window.location.hash = 1;document.title = document.height;"
onNavigationStateChange={this.onWebViewNavigationStateChange.bind(this)}
/>
...
onWebViewNavigationStateChange(navState) {
// navState.title == height on iOS and html content on android
if (navState.title) {
this.setState({
webViewHeight: Number(navState.title)
});
}
}
...
But on android the value of the title inside onWebViewNavigationStateChange is equal to page content.
What am I doing wrong?

I was baffled by this too. It actually works but it's hard to debug why it does not work because Chrome remote debugging is not enabled for the React Native WebViews on Android.
I had two issues with this:
The script I injected to the Webview contained some single line comments and on Android all the line breaks are removed (another bug?). It caused syntax errors in the WebView.
On the first call the title content indeed is the full content of the Webview. No idea why but on latter calls it's the height. So just handle that case.
Here's the code I'm using now which on works on React Native 0.22 on Android and iOS
import React, {WebView, View, Text} from "react-native";
const BODY_TAG_PATTERN = /\<\/ *body\>/;
// Do not add any comments to this! It will break line breaks will removed for
// some weird reason.
var script = `
;(function() {
var wrapper = document.createElement("div");
wrapper.id = "height-wrapper";
while (document.body.firstChild) {
wrapper.appendChild(document.body.firstChild);
}
document.body.appendChild(wrapper);
var i = 0;
function updateHeight() {
document.title = wrapper.clientHeight;
window.location.hash = ++i;
}
updateHeight();
window.addEventListener("load", function() {
updateHeight();
setTimeout(updateHeight, 1000);
});
window.addEventListener("resize", updateHeight);
}());
`;
const style = `
<style>
body, html, #height-wrapper {
margin: 0;
padding: 0;
}
#height-wrapper {
position: absolute;
top: 0;
left: 0;
right: 0;
}
</style>
<script>
${script}
</script>
`;
const codeInject = (html) => html.replace(BODY_TAG_PATTERN, style + "</body>");
/**
* Wrapped Webview which automatically sets the height according to the
* content. Scrolling is always disabled. Required when the Webview is embedded
* into a ScrollView with other components.
*
* Inspired by this SO answer http://stackoverflow.com/a/33012545
* */
var WebViewAutoHeight = React.createClass({
propTypes: {
source: React.PropTypes.object.isRequired,
injectedJavaScript: React.PropTypes.string,
minHeight: React.PropTypes.number,
onNavigationStateChange: React.PropTypes.func,
style: WebView.propTypes.style,
},
getDefaultProps() {
return {minHeight: 100};
},
getInitialState() {
return {
realContentHeight: this.props.minHeight,
};
},
handleNavigationChange(navState) {
if (navState.title) {
const realContentHeight = parseInt(navState.title, 10) || 0; // turn NaN to 0
this.setState({realContentHeight});
}
if (typeof this.props.onNavigationStateChange === "function") {
this.props.onNavigationStateChange(navState);
}
},
render() {
const {source, style, minHeight, ...otherProps} = this.props;
const html = source.html;
if (!html) {
throw new Error("WebViewAutoHeight supports only source.html");
}
if (!BODY_TAG_PATTERN.test(html)) {
throw new Error("Cannot find </body> from: " + html);
}
return (
<View>
<WebView
{...otherProps}
source={{html: codeInject(html)}}
scrollEnabled={false}
style={[style, {height: Math.max(this.state.realContentHeight, minHeight)}]}
javaScriptEnabled
onNavigationStateChange={this.handleNavigationChange}
/>
{process.env.NODE_ENV !== "production" &&
<Text>Web content height: {this.state.realContentHeight}</Text>}
</View>
);
},
});
export default WebViewAutoHeight;
As gist https://gist.github.com/epeli/10c77c1710dd137a1335

Loading a local HTML file on the device and injecting JS was the only method I found to correctly set the title / hash in Android.
/app/src/main/assets/blank.html
<!doctype html>
<html>
<head>
<title id="title">Go Web!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
</style>
</head>
<body>
<div id="content"></div>
<script>
var content = document.getElementById('content');
var fireEvent = function(event, data) {
document.title = data;
window.location.hash = event;
};
var setContent = function(html) {
content.innerHTML = html;
};
</script>
</body>
</html>
And the component
class ResizingWebView extends Component {
constructor(props) {
super(props)
this.state = {
height: 0
}
}
onNavigationStateChange(navState) {
var event = navState.url.split('#')[1]
var data = navState.title
console.log(event, data)
if (event == 'resize') {
this.setState({ height: data })
}
}
render() {
var scripts = "setContent('<h1>Yay!</h1>');fireEvent('resize', '300')";
return (
<WebView
source={{ uri: 'file:///android_asset/blank.html' }}
injectedJavaScript={ scripts }
scalesPageToFit={ false }
style={{ height: this.state.height }}
onNavigationStateChange={ this.onNavigationStateChange.bind(this) }
/>
)
}
}

Related

How to clear the google map markers before refreshing with a new map? [duplicate]

This question already has answers here:
Google Maps API v3: How to remove all markers?
(32 answers)
Closed 4 years ago.
Could someone be kind enough to share how I can clear the markers in google map before refreshing it with a new set of markers?
In my map, I'm adding markers from an array that contains name, lat and long. The name can be picked from a drop down menu, and then all the markers for that name are added to the page.
Prtoject : Asp.Net Mvc
Link image: https://i.hizliresim.com/V927Py.jpg
When the user adds markers, the previous set of markers remain. I'd like to remove any existing markers before adding the new set.
After reading the documentation, I tried this:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model List<Project_Map.Models.KONUM>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Marker Icons</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<style>
#map_wrapper {
height: 700px;
}
#map_canvas {
width: 100%;
height: 100%;
}
</style>
<div id="map_wrapper">
<div class="mapping" id="map_canvas">
</div>
</div>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
jQuery(function ($) {
var script = document.createElement('script');
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBT56XlfxnK2OB4K93vWdrZci_CKjZyQOM&callback=initMap";
document.body.appendChild(script);
});
</script>
<!-- Google Maps Kodu -->
<script type="text/javascript">
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'<img src="#IMG_SRC#" />' +
'</div>' +
//'<h2 id="firstHeading" class="firstHeading">#PERSONEL#</h2>' +
'<div id="bodyContent">' +
'<b>Mesafe: </b>#MESAFE# Km<br />' +
'<b>Tarih: </b> #TARIH#' +
'</p>' +
'</div>' +
'</div>';
$(document).ready(function () {
initMap();
});
function initMap() {
var mapCenter = { lat: 39.684536, lng: 35.337094 };
var map = new google.maps.Map(document.getElementById('map_wrapper'), {
zoom: 6,// haritanın yakınlık derecesi
center: mapCenter, // haritanın merkezi
mapTypeId: google.maps.MapTypeId.HYBRID
});
var infoWindow = new google.maps.InfoWindow();
setInterval(function () {
$.ajax({
url: '#Url.Action("GetMapLocations", "Konum")',
type: "POST",
success: function (data) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var position = {
lat: parseFloat(json[i].lat.replace(',', '.')),
lng: parseFloat(json[i].lng.replace(',', '.'))
};
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.BOUNCE,
map: map,
});
// infoWindow içeriğini replace et
var cs = contentString;
cs = cs.replace("#PERSONEL#", json[i].name);
cs = cs.replace("#MESAFE#", json[i].mesafe);
cs = cs.replace("#TARIH#", json[i].tarih);
cs = cs.replace("#IMG_SRC#", json[i].img);
google.maps.event.addListener(marker, 'click', (function (marker, cs, infoWindow) {
return function () {
infoWindow.setContent(cs);
infoWindow.open(map, this);
passive: true;
};
})(marker, cs, infoWindow));
};
},
error: function (data) { alert("Malesef Sunucunuza Ulaşamıyoruz. Lütfen Tekrar Deneyiniz..."); },
});
}, 5000);
};
</script>
</body>
</html>
You have to set up an array, where you can store the added marker
var gmarkers = [];
If you add a marker you have to store the marker object in the array.
gmarkers.push(marker);
If you want to remove these markers you can use something like:
function removeMarker() {
if (gmarkers.length > 0) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i] != null) {
gmarkers[i].setMap(null);
}
}
}
gmarkers = [];
}

React.createElement : type should not be null

I copied the code from here.
This throws this warning:
.
How to fix this warning?
Code:
'use strict';
var React = require('react-native');
// I have import the ScrollView and RefreshControl
var{
StyleSheet,
Image,
ScrollView,
RefreshControl,
View,
} = React;
var Carousel = require('react-native-looped-carousel');
var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window');
var NewsListView = React.createClass({
getInitialState: function () {
return {
isRefreshing: false,
loaded: 0,
};
},
componentDidMount: function () {
},
render: function () {
return (
// if I remove RefreshControl , the warming missing. how to fix this problem
<ScrollView
style={styles.scrollview}
refreshControl={
<RefreshControl
refreshing={this.state.isRefreshing}
onRefresh={this._onRefresh}
tintColor="#ff0000"
title="Loading..."
/>
}>
<View>
<Carousel delay={5000} style={{width: width, height: height/4 }}>
<Image
source={require('RT_XiaoYiSiGou/Image/img_banner.png')
}
style={{width: width, height: height/4}}
/>
<Image
source={require('RT_XiaoYiSiGou/Image/img_banner2.png')}
style={{width: width, height: height/4}}
/>
<Image
source={require('RT_XiaoYiSiGou/Image/img_banner3.png')}
style={{width: width, height: height/4}}
/>
</Carousel>
</View>
</ScrollView>
);
},
_onRefresh() {
this.setState({isRefreshing: true});
setTimeout(() => {
this.setState({
loaded: this.state.loaded + 10,
isRefreshing: false,
});
}, 5000);
},
});
var styles = StyleSheet.create({
scrollview: {
flex: 1,
},
});
module.exports = NewsListView;
What I "suggest" because I can't do more from your code is:
1) The error you get is because you do not call the React.createElement correctly. You should write your code in simple segments, I suggest chopping it up in three parts, definition, creation and render...
// define your element
var definitionObject = {
// a property called render which is a function which returns your markup.
render: function() {
return (
<h1 className="peterPan">
Peter Pan.
</h1>
);
}
}
// create the actual element
var PeterPanElement = React.createClass(definitionObject);
ReactDOM.render(
<PeterPanElement />,
document.getElementById('willBeReplacedByPeterPanElement')
);
I hope you agree I can't deduce more from your question, if you clean the question up we might be able to help you out more...

Moving elements by dragging in Dart

I am trying to move an element using drag and drop. I want to be able to drag and element to a different location, and when I drop it, the element moves to the dropped location. Super basic, and nothing fancy. This is what I have so far:
html:
<input type='button' id='drag' class='draggable' value='drag me' draggable='true'>
Dart code:
Element drag = querySelector('.draggable');
drag.onDragEnd.listen((MouseEvent e) {
drag.style.left = '${e.client.x}px';
drag.style.top = '${e.client.y}px';
});
This doesn't quite do what I want it to do. The element is slightly off from where I drop it. I see examples in javascript with appendChild, clone(), parentNode, but none of the examples that I have seen can be reproduced in Dart. What is the best way to accomplish this? I don't want to use the DND package, since I am really trying to personally understand the concepts better.
index.html
<!doctype html>
<html>
<head>
<style>
#dropzone {
position: absolute;
top: 50px;
left: 50px;
width: 300px;
height: 150px;
border: solid 1px lightgreen;
}
#dropzone.droptarget {
background-color: lime;
}
</style>
</head>
<body>
<input type='button' id='drag' class='draggable' value='drag me'
draggable='true'>
<div id="dropzone"></div>
<script type="application/dart" src="index.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
index.dart
library _template.web;
import 'dart:html' as dom;
import 'dart:convert' show JSON;
main() async {
dom.Element drag = dom.querySelector('.draggable');
drag.onDragStart.listen((event) {
final startPos = (event.target as dom.Element).getBoundingClientRect();
final data = JSON.encode({
'id': (event.target as dom.Element).id,
'x': event.client.x - startPos.left,
'y': event.client.y - startPos.top
});
event.dataTransfer.setData('text', data);
});
dom.Element dropTarget = dom.querySelector('#dropzone');
dropTarget.onDragOver.listen((event) {
event.preventDefault();
dropTarget.classes.add('droptarget');
});
dropTarget.onDragLeave.listen((event) {
event.preventDefault();
dropTarget.classes.remove('droptarget');
});
dropTarget.onDrop.listen((event) {
event.preventDefault();
final data = JSON.decode(event.dataTransfer.getData('text'));
final drag = dom.document.getElementById(data['id']);
event.target.append(drag);
drag.style
..position = 'absolute'
..left = '${event.offset.x - data['x']}px'
..top = '${event.offset.y - data['y']}px';
dropTarget.classes.remove('droptarget');
});
}
The answer above is correct, and I didn't want to edit it for that reason. However, I wanted to also offer another answer that I derived from the above. It is a lot more basic compared to the above, and so easier to follow the basic concepts for beginners. As mentioned below, I don't think you can move elements unless they are within a droppable area.
index.html:
<!DOCTYPE html>
<html>
<head>
<style>
#dropzone {
position: absolute;
top: 100px;
left: 50px;
width: 300px;
height: 150px;
border: solid 1px;
color: lightgreen;
}</style>
</head>
<body>
<div id="dropzone">
<input type='button' id='drag' class='draggable' value='drag me'
draggable='true'>
</div>
<script type="application/dart" src="main.dart"></script>
</body>
</html>
main.dart:
import 'dart:html';
main() {
Element drag = querySelector('.draggable');
Element drop = querySelector('#dropzone');
drag.onDragStart.listen((MouseEvent e) {
var startPos = (e.target as Element).getBoundingClientRect();
String xPos = "${e.client.x - startPos.left}";
String yPos = "${e.client.y - startPos.top}";
e.dataTransfer.setData('x', xPos);
e.dataTransfer.setData('y', yPos);
});
drop.onDragOver.listen((MouseEvent e) {
e.preventDefault();
});
drop.onDrop.listen((MouseEvent e) {
e.stopPropagation();
String xPos = e.dataTransfer.getData('x');
String yPos = e.dataTransfer.getData('y');
int x = num.parse(xPos);
int y = num.parse(yPos);
drag.style.position = 'absolute';
drag.style
..left = '${e.offset.x - x}px'
..top = '${e.offset.y - y}px';
});
}
I had the same question and since the answers above did not meet my needs in:
Element drag-gable by itself(No drop zone)
Reusable
For a wrapper based solution, this package could be the answer:https://pub.dartlang.org/packages/dnd
Custom element based approach(Currently cursor styling is not working):
main(){
document.registerElement('draggable-element',
DraggableElement);
querySelector('body').append(new DraggableElement()..text='draggable');
}
class DraggableElement extends HtmlElement with Draggability{
DraggableElement.created():super.created(){
learn_custom_draggability();
}
factory DraggableElement(){
return new Element.tag('draggable-element');
}
}
class Draggability{
bool __custom_mouseDown = false;
//The Coordinates of the mouse click
//relative to the left top of the
//element.
Point<int> __custom_relative_mouse_position;
void learn_custom_draggability(){
if(this is! HtmlElement ){
throw ("Draggability mixin "
"is not compatible with"
' non-HtmlElement.');
}
var self = (this as HtmlElement);
self.onMouseDown.listen(mouseDownEventHandler);
self.onMouseUp.listen(mouseUpEventHandler);
//styling
self.style.position = 'absolute';
window.onMouseMove
.listen(mouseMoveEventHandler);
}
void mouseMoveEventHandler(MouseEvent e){
if(!__custom_mouseDown) return;
int xoffset = __custom_relative_mouse_position.x,
yoffset = __custom_relative_mouse_position.y;
var self = (this as HtmlElement);
int x = e.client.x-xoffset,
y = e.client.y-yoffset;
print(x);
if(y == 0) return;
self.style
..top = y.toString() +'px'
..left = x.toString()+'px';
}
void mouseDownEventHandler(MouseEvent e){
print('mouse down');
__custom_mouseDown = true;
var self = (this as HtmlElement);
self.style.cursor = 'grabbing';
__custom_relative_mouse_position =
e.offset;
}
void mouseUpEventHandler(MouseEvent e){
print('mouse up');
__custom_mouseDown = false;
var self = (this as HtmlElement);
self.style.cursor = 'default';
}
}
Edit:
Yay, Thank you Günter Zöchbauer for informing me about reflectable. It's so small and compiles fast.
A little off the topic but posting since mixins and the below pattern goes hand in hand.
import 'package:reflectable/reflectable.dart';
class Reflector extends Reflectable{
const Reflector():
super(
instanceInvokeCapability,
declarationsCapability
);
}
const reflector = const Reflector();
#reflector
class CustomBase extends HtmlElement{
CustomBase.created():super.created(){
learn();
}
learn(){
InstanceMirror selfMirror = reflector.reflect(this);
var methods = selfMirror.type.instanceMembers;
RegExp pattern = new RegExp('^learn_custom_.*bility\$');
for(var k in methods.keys){
if(pattern.firstMatch(k.toString()) != null){
selfMirror.invoke(k,[]);
}
}
}
}
Include: "reflectable: ^0.5.0" under dependencies and "- reflectable: entry_points: web/index.dart" etc under transformers
in the pubspec.yaml and extend a custom class like the above instead of a HtmlElement and selfMirror.invoke magically calls your initializer as long as their names match the given pattern. Useful when your classes have a quite few abilities.

Resize event when page have fixed element in iPad Safari

I need to perform a certain function on "resize" event and after the zoom in/zoom out on ipad. First I did oun event and raise "resize" event in listener:
ZoomHelper = (function () {
var zoomListeners = [];
var viewportScale = 1;
var polling = false;
function pollZoomFireEvent() {
var widthNow = window.innerWidth;
currentViewportScale = (window.screen.width / window.innerWidth).toPrecision(3);
if (currentViewportScale != viewportScale) {
viewportScale = currentViewportScale;
for (var i = 0; i < zoomListeners.length; i++) {
zoomListeners[i]();
}
}
if (polling)
setTimeout(arguments.callee, 500);
}
function startPollingIfNeeded() {
if (zoomListeners.length == 1) {
polling = true;
pollZoomFireEvent();
}
}
function stopPollingIfNeeded() {
if (zoomListeners.length < 1) {
polling = false;
}
}
return {
addZoomListener: function (func) {
zoomListeners.push(func);
startPollingIfNeeded();
},
removeZoomListener: function (func) {
index = zoomListeners.indexOf(func);
zoomListeners.slice(index, 1);
stopPollingIfNeeded();
}
}
})();
But later I found that if a page has at least one element with fixed positioning then the "resize" event raise automatically after zoom in or zoom out:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
<script>
window.onresize = onResize;
function onResize(e) {
console.log("resize");
}
</script>
</head>
<body>
<div style="position:fixed; border:5px solid red; width:50px; height:50px;">
</div>
</body>
</html>
Is it normal behaviour? Which of these variants is better to use? Or is there some better way to raise "resize" event after zoom?

How to scroll the checkboxes inside a dropdown by jquery.mobile.scrollview.js?

I have implemented the Jquery.mobile.scrollview.js and i am able to scroll the dropdown,But what happens is when i click to scroll the checkboxes inside the dropdown the checkboxes gets invisible and only the text is shown.. IS there is any workaround is there... Please let me know..
IS there any example on this..... I am adding my code below .. and giving data-scroll = 'y' in my div part ...
<!-- Scroll View code -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#evtCatcher
{
}
#evtCatcher .ui-scrollview-view
{
padding: 10px;
}
</style>
<script src="jsScroll/jquery.js" type="text/javascript"></script>
<script src="jsScroll/jsdefault.js" type="text/javascript"></script>
<script src="jsScroll/jquery.easing.1.3.js" type="text/javascript"></script>
<script src="jsScroll/jquery.mobile.scrollview.js" type="text/javascript"></script>
<script src="jsScroll/iscroll.js" type="text/javascript""></script>
<script type="text/javascript">
function fnClick() {
alert('clicked');
}
</script>
<script>
$("[ data-role=page]").live("pageshow", function(event) {
var $page = $(this);
$page.find("[data-scroll]:not(.ui-scrollview-clip)").each(function() {
var $this = $(this);
// XXX: Remove this check for ui-scrolllistview once we've
// integrated list divider support into the main scrollview class.
if ($this.hasClass("ui-scrolllistview"))
$this.scrolllistview();
else {
var st = $this.data("scroll") + "";
var paging = st && st.search(/^[xy]p$/) != -1;
var dir = st && st.search(/^[xy]/) != -1 ? st.charAt(0) : null;
var opts = {};
if (dir)
opts.direction = dir;
if (paging)
opts.pagingEnabled = true;
$this.scrollview(opts);
}
});
changeDelayFormElementClick();
});
function changeScrollMethod() {
var val = $("#s_method").val();
var $sv = $("#evtCatcher").scrollview("scrollTo", 0, 0);
if (val === "scroll") {
$sv.css("overflow", "scroll");
}
else {
$sv.css("overflow", "hidden");
}
$sv.data("scrollview").options.scrollMethod = val;
}
function changeDelayFormElementClick() {
$("#evtCatcher").data("scrollview").options.delayedClickEnabled = ($("#s_delay").val() === "yes");
}
var cb_hd_pd,
cb_hd_sp,
cb_hm_pd,
cb_hm_sp,
cb_hu_pd,
cb_hu_sp;
var hd = $.mobile.scrollview.prototype._handleDragStart;
var hm = $.mobile.scrollview.prototype._handleDragMove;
var hu = $.mobile.scrollview.prototype._handleDragStop;
function getDummyEvent(o) {
return { target: o.target, _pd: false, _sp: false, preventDefault: function() { this._pd = true; }, stopPropagation: function() { this._sp = true; } };
}
function updateEvent(e, cb_pd, cb_sp) {
if (cb_pd.checked)
e.preventDefault();
if (cb_sp.checked)
e.stopPropagation();
}
$.mobile.scrollview.prototype._handleDragStart = function(e, x, y) {
hd.call(this, getDummyEvent(e), x, y);
updateEvent(e, cb_hd_pd, cb_hd_sp);
};
$.mobile.scrollview.prototype._handleDragMove = function(e, x, y) {
hm.call(this, getDummyEvent(e), x, y);
updateEvent(e, cb_hm_pd, cb_hm_sp);
};
$.mobile.scrollview.prototype._handleDragStop = function(e) {
hu.call(this, getDummyEvent(e));
updateEvent(e, cb_hu_pd, cb_hu_sp);
};
$(function() {
cb_hd_pd = $("#cb_hd_pd")[0];
cb_hd_sp = $("#cb_hd_sp")[0];
cb_hm_pd = $("#cb_hm_pd")[0];
cb_hm_sp = $("#cb_hm_sp")[0];
cb_hu_pd = $("#cb_hu_pd")[0];
cb_hu_sp = $("#cb_hu_sp")[0];
});
</script>
Thanks in Advance :)

Resources