Get the event response of script in WebView to the react native - html

I am using the html script for showing some module. Everthing was going perfect until I got no any response of the eventHandler. How can I get the response of the eventHandler in Web View.I am not getting any log of the onSuccess, onError or onClose methods. I am using react-native-webview. I tried using window.postMessage('onSuccess'); and geting the value on onMessage
this.khaltiUI = `<html>
<head>
<script src="https://khalti.com/static/khalti-checkout.js"></script>
</head>
<body>
<script>
var config = {
// replace the publicKey with yours
"publicKey": "test_public_key_dc74e0fd57cb46cd93832aee0a390234",
"productIdentity": "1234567890",
"productName": "Dragon",
"productUrl": "http://gameofthrones.wikia.com/wiki/Dragons",
"eventHandler": {
onSuccess (payload) {
window.postMessage('onSuccess');
console.log(payload);
},
onError (error) {
window.postMessage('onError')
console.log(error);
},
onClose () {
window.postMessage('onClosed')
console.log('widget is closing');
}
}
};
var checkout = new KhaltiCheckout(config);
checkout.show({amount: 1000, mobile: 9800000000});
</script>
</body>
</html>`
And in the react-native webView component:
<WebView
source={{html: this.khaltiUI }}
originWhitelist={["*"]}
scalesPageToFit={false}
style={{position: 'absolute', top: 0, bottom: 0, right: 0, left: 0}}
onMessage={this.onMessage}
startInLoadingState ={true}
/>
onMessage(event){
console.log('Hello'); //got no any response
console.log(JSON.parse(event.nativeEvent.data));
console.log(event.nativeEvent.data);
}

this what I use for sending data from webview to react-native:
react:
import React, { Component } from "react";
import { WebView } from "react-native-webview";
export default class App extends Component {
_bridge(event) {
if(event.nativeEvent.data == 'exit') {
BackHandler.exitApp();
}
}
render() {
return (
<WebView
style={{flex: 1}}
source={{ uri: "https://www.kende.com/" }}
onMessage={event => { this._bridge(event); }}
/>
);
}
}
html:
<script>
$( document ).ready(function() {
$('#exit').on('click', function(){
window.ReactNativeWebView.postMessage("exit");
});
});
</script>
<span id="exit">Exit</span>

To post data to a web page, first, you have to get the ref of WebView:
<WebView
ref={(webView) => this.webView = webView}
onMessage={this.onMessage}
...
/>
Then post a message like:
sendPostMessage() {
console.log("Sending post message");
this.webView.postMessage("Post message from react native");
}

Related

Nuxt is returning html instead of JSON that I got from the api

I have a simple api returning a json object that I want to display unto the screen.
However when I display the $data property I'm getting html and not the json from the api.
However whenever I refresh the page with f5 or manually the data then shows up on the screen and not the html.
{
"data": {
"positions": 2,
"departments": 2,
"paygrades": 8
}
}
<template>
<v-container>
<v-row> {{ $data.dbData }}</v-row>
</v-container>
</template>
<script>
export default {
async asyncData({ $axios }) {
const dbData = await $axios.$get('/dashboard')
return dbData
},
data() {
return {
}
},
}
</script>
Edited code
<template>
<v-container>
<v-row> {{ dbData }}</v-row>
</v-container>
</template>
<script>
export default {
data() {
return {
dbData: null,
}
},
async fetch() {
this.dbData = await this.$axios.$get('/dashboard')
},
}
</script>

Vue.js: Dynamically render html in child component's slot

In my vue.js application, I am trying to render the html content dynamically in child component's slot. If I enter the text only then there is no issue, it works with fine.
Here is my code:
ChildComponent.vue
<template>
<div :class="type" class="message" v-if="type">
<slot />
</div>
</template>
<script>
export default {
...
props: ['type'],
...
}
</script>
ParentComponent.vue
<script>
import Alert from '#/Alert';
export default {
components: {
Alert,
},
data() {
return {
...
alert: {
error: '',
message: '',
}
};
},
created () {
this._onLoad()
},
methods: {
_onLoad() {
axios.get(`api.call.here`).then((res) => {
...
}).catch(error => {
this.alert.error = error.type;
this.alert.message = `<p>message here</p>`; // from response
});
},
}
}
</script>
Here is the screenshot of the issue:
What you trying to do can be achieved with v-html. You can use it while calling your ChildComponent.vue. This is a small example for your case:
<Alert>
<span v-html="alert.message"></span>
</Alert>

Initializing Google Maps inside component but inside certain element

I using this tutorial to use Google maps API https://markus.oberlehner.net/blog/using-the-google-maps-api-with-vue/ and it is working well. But it use this.$el to load the Google map instance inside the component and that makes take all screen, I want to load inside .map instead so I can have smaller map.
<template>
<div class="container-fluid">
init map
<div class="map">
</div>
</div>
</template>
<script>
import ProgressSpinner from '.././Preloader';
import { mapGetters } from 'vuex'
import gmapsInit from '../.././utils/gmaps';
export default {
name: 'Tracking',
data: () => ({
}),
async mounted() {
$('.container-fluid').bootstrapMaterialDesign();
try {
const google = await gmapsInit();
const geocoder = new google.maps.Geocoder();
const map = new google.maps.Map(this.$el);
geocoder.geocode({ address: 'Austria' }, (results, status) => {
if (status !== 'OK' || !results[0]) {
throw new Error(status);
}
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
});
} catch (error) {
console.error('Error with calling Google maps API: ',error);
}
},
computed: {
...mapGetters([])
},
created(){
this.$store.dispatch ('allPoints')
.then(()=> console.log('points'))
.catch( () => console.log('no poiints ') )
},
methods: {
},
components: {
ProgressSpinner
}
}
</script>
<style scoped>
.map {
width: 150px;
}
</style>
The problem with style, so I should have added height to the .map element.

how do you render GoogleMaps API to a route-specific HTML Div element?

I'm using React Meteor 1.3 and this google maps package.
https://github.com/dburles/meteor-google-maps-react-example.
I can successfully render the map to a single page App, however as soon as I add routing to the mix - things stop working. Specifically when I move the element from an index html template to a JSX component that renders to the page - it breaks. I'm at a bit of a loss here and as the problem is quite vague (in my mind at least) I can't find an answer on google.
What's happening here? Does anyone have an example of this package working with flowrouter?
My current working set up looks like this.
Map.jsx
import React from 'react';
import ReactDOM from 'react-dom';
MyTestMap = React.createClass({
mixins: [ReactMeteorData],
componentDidMount() {
GoogleMaps.load();
},
getMeteorData() {
return {
loaded: GoogleMaps.loaded(),
mapOptions: GoogleMaps.loaded() && this._mapOptions()
};
},
_mapOptions() {
return {
center: new google.maps.LatLng(-37.8136, 144.9631),
zoom: 8
};
},
render() {
if (this.data.loaded)
return <GoogleMap name="mymap" options={this.data.mapOptions} />;
return <div>Loading map...</div>;
}
});
GoogleMap = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired,
options: React.PropTypes.object.isRequired
},
componentDidMount() {
GoogleMaps.create({
name: this.props.name,
element: ReactDOM.findDOMNode(this),
options: this.props.options
});
GoogleMaps.ready(this.props.name, function(map) {
var marker = new google.maps.Marker({
position: map.options.center,
map: map.instance
});
});
},
componentWillUnmount() {
if (GoogleMaps.maps[this.props.name]) {
google.maps.event.clearInstanceListeners(GoogleMaps.maps[this.props.name].instance);
delete GoogleMaps.maps[this.props.name];
}
},
render() {
return (
<div id="mapId" className="map-container"></div>
)
}
});
if (Meteor.isClient) {
Meteor.startup(function() {
return ReactDOM.render(<MyTestMap />, document.getElementById('root'));
});
}
And then I render this to an Index.html file - however this means that the map is on every page.
<head>
<title>googlemaps-react</title>
</head>
<body>
<div id="root"></div>
</body>
Thanks

How to access polymer when "this" becomes "that"

I am trying to integrate dropzone.js and cloudinary into Polymer 1.0. It does work, but I am hitting a stumbling block on how to send the dynamic URL generated by Cloudinary back to Polymer so I can write that URL into Firebase. I am inside a function listening to dropzone events with the intention of using iron-signals to signal a different web component. "this" is now scoped to dropzone.js and not Polymer.
..resulting in "Uncaught TypeError: this.fire is not a function".
The code is below, I am trying to start the iron-signal based on listening the dropzone.js "success" event which provides access to the new image URL.
<link rel="stylesheet" href="../../../bower_components/dropzone/dist/min/dropzone.min.css">
<dom-module id="my-dropzone">
<style>
:host {
display: block;
}
div#my-dropzone-area {
max-width=300px;
height=300px;
border: 4px dashed blue;
}
</style>
<template>
<paper-button on-tap="startTheMessage">Test Fire!</paper-button>
<iron-signals on-iron-signal-hello="passTheMessage">
<div class="dropzone" id="my-dropzone-area">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'my-dropzone',
ready: function() {
// access a local DOM element by ID using this.$
Dropzone.options.myDropzoneArea = {
paramName: 'file', // The name that will be used to transfer the file
maxFilesize: 10, // MB
uploadMultiple: false,
acceptedFiles: '.jpg,.png,.jpeg,.gif',
parallelUploads: 6,
addRemoveLinks: true,
url: 'https://api.cloudinary.com/v1_1/remarkable-ky/image/upload',
init: function() {
this.on('addedfile', function(file) {
console.log('Added file.');
console.log(file);
});
this.on('sending', function(file, xhr, formData) {
console.log('Sending file.');
formData.append('api_key', 0000000000000);
formData.append('timestamp', Date.now() / 1000);
formData.append('upload_preset', 'where-ky');
});
this.on('success', function(file, response) {
var baseURL = 'http://res.cloudinary.com/remarkable-ky/image/upload/';
var url = baseURL.concat(response.public_id);
console.log('Cloudinary URL: ', url);
this.fire('iron-signal', {
name: 'hello',
data: null
});
});
}
};
},
startTheMessage: function() {
this.fire('iron-signal', {
name: 'hello',
data: null
});
},
passTheMessage: function() {
alert("got it");
},
properties: {},
});
})();
</script>
<script src="../../../bower_components/dropzone/dist/min/dropzone.min.js"></script>
you can pass this into the function with the .bind() function.
this.on('success', function(file, response) {
var baseURL = 'http://res.cloudinary.com/remarkable-ky/image/upload/';
var url = baseURL.concat(response.public_id);
console.log('Cloudinary URL: ', url);
this.fire('iron-signal', {
name: 'hello',
data: null
});
}.bind(this));