Dispatch action in injectedJavascript of Android device WebView in React Native not working
i have 1 html and i need get all src attribute of image tag. Everything is running perfect(iOS, Android Virtual machine, iOS device), but only Android Device, I can't get src attribute!! Please help me! Thanks!!
My WebView
render() {
const { source, style, ...otherProps } = this.props;
const { realContentHeight } = this.state;
const html = source.html;
const number = this.addHeight(html);
const addHeightMore = number * 220;
return (
<View style={{ flex: 1 }}>
<View
style={{
paddingHorizontal: 5,
}}
>
<WebView
{...otherProps}
source={{
html:`
<head></head>
<body style="font-size: ${sizeText}; text-align: left; padding: 5">
${templates[this.props.template](html)}
</body>
`
}}
onLoad={this.onLoad.bind(this)}
injectedJavaScript={this.injectedJavaScript()}
mixedContentMode={'compatibility'}
onMessage={this.onMessage.bind(this)}
scrollEnabled={false}
style={[{ height: Platform.OS === 'ios' ? realContentHeight : realContentHeight < screenHeight ? screenHeight : realContentHeight + addHeightMore}, style]}
javaScriptEnabled
/>
</View>
</View>
)
}
injectedJavascript()
injectedJavaScript() {
return `
${this.hackBefore()}
function dispatchAction(action, params) {
window.postMessage(JSON.stringify({
action,
params,
}));
};
var imgs = ;
document.querySelectorAll('img:not(.emoji):not(.embedded-img):not(.embedded-btn)').forEach(function (img, index) {
var src = img.getAttribute('src');
imgs.push(src);
img.addEventListener('click', function (event) {
dispatchAction('openGallery', {
index: index,
});
});
});
dispatchAction('addImages', {
imgs: imgs,
});
${this.hackAfter()}
`
}
hackBefore
hackBefore() {
return Platform.OS === 'ios' ?
(function(){
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
:
if (window.postMessage.length !== 1) {
window.postMessage = function(msg) {
setTimeout(function () {
console.log('window.postMessage not ready');
window.postMessage(msg);
}, 500);
}
}
}
hackAfter()
hackAfter() {
return Platform.OS === 'ios' ? '})();' : ''
}
onMessage()
onMessage(event) {
const { action, params } = JSON.parse(event.nativeEvent.data)
switch (action) {
case 'heightCaculated': {
return this.setState({
realContentHeight: params.height,
isRendering: false,
})
}
case 'addImages': {
this.props.resetImages()
// Prefetch image
params.imgs.map(img => Image.prefetch(img))
return this.props.addImages(params.imgs)
}
case 'openGallery':
return navigator.navigate('Gallery', {
index: params.index,
})
default:
return null
}
}
redux
export default connect(null, {
addImages,
resetImages,
})(WebViewAutoHeight)
react-native webview android-webview
add a comment |
i have 1 html and i need get all src attribute of image tag. Everything is running perfect(iOS, Android Virtual machine, iOS device), but only Android Device, I can't get src attribute!! Please help me! Thanks!!
My WebView
render() {
const { source, style, ...otherProps } = this.props;
const { realContentHeight } = this.state;
const html = source.html;
const number = this.addHeight(html);
const addHeightMore = number * 220;
return (
<View style={{ flex: 1 }}>
<View
style={{
paddingHorizontal: 5,
}}
>
<WebView
{...otherProps}
source={{
html:`
<head></head>
<body style="font-size: ${sizeText}; text-align: left; padding: 5">
${templates[this.props.template](html)}
</body>
`
}}
onLoad={this.onLoad.bind(this)}
injectedJavaScript={this.injectedJavaScript()}
mixedContentMode={'compatibility'}
onMessage={this.onMessage.bind(this)}
scrollEnabled={false}
style={[{ height: Platform.OS === 'ios' ? realContentHeight : realContentHeight < screenHeight ? screenHeight : realContentHeight + addHeightMore}, style]}
javaScriptEnabled
/>
</View>
</View>
)
}
injectedJavascript()
injectedJavaScript() {
return `
${this.hackBefore()}
function dispatchAction(action, params) {
window.postMessage(JSON.stringify({
action,
params,
}));
};
var imgs = ;
document.querySelectorAll('img:not(.emoji):not(.embedded-img):not(.embedded-btn)').forEach(function (img, index) {
var src = img.getAttribute('src');
imgs.push(src);
img.addEventListener('click', function (event) {
dispatchAction('openGallery', {
index: index,
});
});
});
dispatchAction('addImages', {
imgs: imgs,
});
${this.hackAfter()}
`
}
hackBefore
hackBefore() {
return Platform.OS === 'ios' ?
(function(){
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
:
if (window.postMessage.length !== 1) {
window.postMessage = function(msg) {
setTimeout(function () {
console.log('window.postMessage not ready');
window.postMessage(msg);
}, 500);
}
}
}
hackAfter()
hackAfter() {
return Platform.OS === 'ios' ? '})();' : ''
}
onMessage()
onMessage(event) {
const { action, params } = JSON.parse(event.nativeEvent.data)
switch (action) {
case 'heightCaculated': {
return this.setState({
realContentHeight: params.height,
isRendering: false,
})
}
case 'addImages': {
this.props.resetImages()
// Prefetch image
params.imgs.map(img => Image.prefetch(img))
return this.props.addImages(params.imgs)
}
case 'openGallery':
return navigator.navigate('Gallery', {
index: params.index,
})
default:
return null
}
}
redux
export default connect(null, {
addImages,
resetImages,
})(WebViewAutoHeight)
react-native webview android-webview
add a comment |
i have 1 html and i need get all src attribute of image tag. Everything is running perfect(iOS, Android Virtual machine, iOS device), but only Android Device, I can't get src attribute!! Please help me! Thanks!!
My WebView
render() {
const { source, style, ...otherProps } = this.props;
const { realContentHeight } = this.state;
const html = source.html;
const number = this.addHeight(html);
const addHeightMore = number * 220;
return (
<View style={{ flex: 1 }}>
<View
style={{
paddingHorizontal: 5,
}}
>
<WebView
{...otherProps}
source={{
html:`
<head></head>
<body style="font-size: ${sizeText}; text-align: left; padding: 5">
${templates[this.props.template](html)}
</body>
`
}}
onLoad={this.onLoad.bind(this)}
injectedJavaScript={this.injectedJavaScript()}
mixedContentMode={'compatibility'}
onMessage={this.onMessage.bind(this)}
scrollEnabled={false}
style={[{ height: Platform.OS === 'ios' ? realContentHeight : realContentHeight < screenHeight ? screenHeight : realContentHeight + addHeightMore}, style]}
javaScriptEnabled
/>
</View>
</View>
)
}
injectedJavascript()
injectedJavaScript() {
return `
${this.hackBefore()}
function dispatchAction(action, params) {
window.postMessage(JSON.stringify({
action,
params,
}));
};
var imgs = ;
document.querySelectorAll('img:not(.emoji):not(.embedded-img):not(.embedded-btn)').forEach(function (img, index) {
var src = img.getAttribute('src');
imgs.push(src);
img.addEventListener('click', function (event) {
dispatchAction('openGallery', {
index: index,
});
});
});
dispatchAction('addImages', {
imgs: imgs,
});
${this.hackAfter()}
`
}
hackBefore
hackBefore() {
return Platform.OS === 'ios' ?
(function(){
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
:
if (window.postMessage.length !== 1) {
window.postMessage = function(msg) {
setTimeout(function () {
console.log('window.postMessage not ready');
window.postMessage(msg);
}, 500);
}
}
}
hackAfter()
hackAfter() {
return Platform.OS === 'ios' ? '})();' : ''
}
onMessage()
onMessage(event) {
const { action, params } = JSON.parse(event.nativeEvent.data)
switch (action) {
case 'heightCaculated': {
return this.setState({
realContentHeight: params.height,
isRendering: false,
})
}
case 'addImages': {
this.props.resetImages()
// Prefetch image
params.imgs.map(img => Image.prefetch(img))
return this.props.addImages(params.imgs)
}
case 'openGallery':
return navigator.navigate('Gallery', {
index: params.index,
})
default:
return null
}
}
redux
export default connect(null, {
addImages,
resetImages,
})(WebViewAutoHeight)
react-native webview android-webview
i have 1 html and i need get all src attribute of image tag. Everything is running perfect(iOS, Android Virtual machine, iOS device), but only Android Device, I can't get src attribute!! Please help me! Thanks!!
My WebView
render() {
const { source, style, ...otherProps } = this.props;
const { realContentHeight } = this.state;
const html = source.html;
const number = this.addHeight(html);
const addHeightMore = number * 220;
return (
<View style={{ flex: 1 }}>
<View
style={{
paddingHorizontal: 5,
}}
>
<WebView
{...otherProps}
source={{
html:`
<head></head>
<body style="font-size: ${sizeText}; text-align: left; padding: 5">
${templates[this.props.template](html)}
</body>
`
}}
onLoad={this.onLoad.bind(this)}
injectedJavaScript={this.injectedJavaScript()}
mixedContentMode={'compatibility'}
onMessage={this.onMessage.bind(this)}
scrollEnabled={false}
style={[{ height: Platform.OS === 'ios' ? realContentHeight : realContentHeight < screenHeight ? screenHeight : realContentHeight + addHeightMore}, style]}
javaScriptEnabled
/>
</View>
</View>
)
}
injectedJavascript()
injectedJavaScript() {
return `
${this.hackBefore()}
function dispatchAction(action, params) {
window.postMessage(JSON.stringify({
action,
params,
}));
};
var imgs = ;
document.querySelectorAll('img:not(.emoji):not(.embedded-img):not(.embedded-btn)').forEach(function (img, index) {
var src = img.getAttribute('src');
imgs.push(src);
img.addEventListener('click', function (event) {
dispatchAction('openGallery', {
index: index,
});
});
});
dispatchAction('addImages', {
imgs: imgs,
});
${this.hackAfter()}
`
}
hackBefore
hackBefore() {
return Platform.OS === 'ios' ?
(function(){
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
:
if (window.postMessage.length !== 1) {
window.postMessage = function(msg) {
setTimeout(function () {
console.log('window.postMessage not ready');
window.postMessage(msg);
}, 500);
}
}
}
hackAfter()
hackAfter() {
return Platform.OS === 'ios' ? '})();' : ''
}
onMessage()
onMessage(event) {
const { action, params } = JSON.parse(event.nativeEvent.data)
switch (action) {
case 'heightCaculated': {
return this.setState({
realContentHeight: params.height,
isRendering: false,
})
}
case 'addImages': {
this.props.resetImages()
// Prefetch image
params.imgs.map(img => Image.prefetch(img))
return this.props.addImages(params.imgs)
}
case 'openGallery':
return navigator.navigate('Gallery', {
index: params.index,
})
default:
return null
}
}
redux
export default connect(null, {
addImages,
resetImages,
})(WebViewAutoHeight)
react-native webview android-webview
react-native webview android-webview
edited Nov 15 '18 at 9:17
longnk
asked Nov 15 '18 at 9:11
longnklongnk
13
13
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
When running your application on an Android device, in production, you must build your HTML file to the Android asset directory - android/app/src/main/assets/index.html
Your WebView
source should then point to this file, file:///android_asset/index.html
. But only on certain conditions
If you are on Android, and you're running in Production the source should be file:///android_asset/index.html
. Else, point your source to your local HTML file.
Here's an example, I am not sure how your project is structured but you can cherrypick what you need.
import React from 'react';
import { Platform, WebView } from 'react-native';
import localFile from '../index.html';
const MyWebView extends React.Component {
isAndroid = () => Platform.OS === "android"
isDev = () => __DEV__
getSource = () => {
if(this.isAndroid() && !this.isDev()) {
return { uri: 'file:///android_asset/index.html' };
}
return localFile
}
render() {
<WebView
source={this.getSource()}
/>
}
}
Thanks Dan, but it's not working!!
– longnk
Nov 16 '18 at 1:31
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53315899%2fdispatch-action-in-injectedjavascript-of-android-device-webview-in-react-native%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
When running your application on an Android device, in production, you must build your HTML file to the Android asset directory - android/app/src/main/assets/index.html
Your WebView
source should then point to this file, file:///android_asset/index.html
. But only on certain conditions
If you are on Android, and you're running in Production the source should be file:///android_asset/index.html
. Else, point your source to your local HTML file.
Here's an example, I am not sure how your project is structured but you can cherrypick what you need.
import React from 'react';
import { Platform, WebView } from 'react-native';
import localFile from '../index.html';
const MyWebView extends React.Component {
isAndroid = () => Platform.OS === "android"
isDev = () => __DEV__
getSource = () => {
if(this.isAndroid() && !this.isDev()) {
return { uri: 'file:///android_asset/index.html' };
}
return localFile
}
render() {
<WebView
source={this.getSource()}
/>
}
}
Thanks Dan, but it's not working!!
– longnk
Nov 16 '18 at 1:31
add a comment |
When running your application on an Android device, in production, you must build your HTML file to the Android asset directory - android/app/src/main/assets/index.html
Your WebView
source should then point to this file, file:///android_asset/index.html
. But only on certain conditions
If you are on Android, and you're running in Production the source should be file:///android_asset/index.html
. Else, point your source to your local HTML file.
Here's an example, I am not sure how your project is structured but you can cherrypick what you need.
import React from 'react';
import { Platform, WebView } from 'react-native';
import localFile from '../index.html';
const MyWebView extends React.Component {
isAndroid = () => Platform.OS === "android"
isDev = () => __DEV__
getSource = () => {
if(this.isAndroid() && !this.isDev()) {
return { uri: 'file:///android_asset/index.html' };
}
return localFile
}
render() {
<WebView
source={this.getSource()}
/>
}
}
Thanks Dan, but it's not working!!
– longnk
Nov 16 '18 at 1:31
add a comment |
When running your application on an Android device, in production, you must build your HTML file to the Android asset directory - android/app/src/main/assets/index.html
Your WebView
source should then point to this file, file:///android_asset/index.html
. But only on certain conditions
If you are on Android, and you're running in Production the source should be file:///android_asset/index.html
. Else, point your source to your local HTML file.
Here's an example, I am not sure how your project is structured but you can cherrypick what you need.
import React from 'react';
import { Platform, WebView } from 'react-native';
import localFile from '../index.html';
const MyWebView extends React.Component {
isAndroid = () => Platform.OS === "android"
isDev = () => __DEV__
getSource = () => {
if(this.isAndroid() && !this.isDev()) {
return { uri: 'file:///android_asset/index.html' };
}
return localFile
}
render() {
<WebView
source={this.getSource()}
/>
}
}
When running your application on an Android device, in production, you must build your HTML file to the Android asset directory - android/app/src/main/assets/index.html
Your WebView
source should then point to this file, file:///android_asset/index.html
. But only on certain conditions
If you are on Android, and you're running in Production the source should be file:///android_asset/index.html
. Else, point your source to your local HTML file.
Here's an example, I am not sure how your project is structured but you can cherrypick what you need.
import React from 'react';
import { Platform, WebView } from 'react-native';
import localFile from '../index.html';
const MyWebView extends React.Component {
isAndroid = () => Platform.OS === "android"
isDev = () => __DEV__
getSource = () => {
if(this.isAndroid() && !this.isDev()) {
return { uri: 'file:///android_asset/index.html' };
}
return localFile
}
render() {
<WebView
source={this.getSource()}
/>
}
}
answered Nov 15 '18 at 9:23
DanDan
2,40111329
2,40111329
Thanks Dan, but it's not working!!
– longnk
Nov 16 '18 at 1:31
add a comment |
Thanks Dan, but it's not working!!
– longnk
Nov 16 '18 at 1:31
Thanks Dan, but it's not working!!
– longnk
Nov 16 '18 at 1:31
Thanks Dan, but it's not working!!
– longnk
Nov 16 '18 at 1:31
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53315899%2fdispatch-action-in-injectedjavascript-of-android-device-webview-in-react-native%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown