【发布时间】:2018-10-19 14:08:27
【问题描述】:
在我的 React Native 应用程序中,我使用“injectedJavascript”道具使用 WebView 来显示谷歌广告 (AdSense)。问题是我无法提前知道广告的高度。所以我一开始给它一个随机高度,当它的样式更新时,我打算正确设置它的高度。
我假设我必须在注入的 JS 代码中获取高度,然后使用“window.postMessage()”方法通过“onMessage”属性将其发送到 WebView。
MutationObserver 结合 promise 似乎非常适合这种情况。现在,我只想接收来自 webview 的消息。所以这是我现在的代码,但没有发送任何消息:
export default class App extends Component {
constructor(props) {
super(props);
}
_onMessage(e) {
console.warn(e.nativeEvent.data);
}
render() {
const jsCode = `
window._googCsa('ads', pageOptions, adblock1);
function waitForAdSense(id) {
var config = {
attributes: true,
attributeFilter: ['style'],
};
return new Promise((resolve, reject) => {
var adSenseElement = document.body.getElementById(id);
if (adSenseElement.style) {
resolve(adSenseElement.style.height);
return;
}
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName === 'style') {
observer.disconnect();
resolve(adSenseElement);
return;
}
});
});
observer.observe(adSenseElement, config);
});
}
waitForAdSense('afscontainer1').then(height => {
window.postMessage(height, '*');
});
`;
return (
<ScrollView>
<WebView
key={'AdSense'}
ref={'webview2'}
style={{ height: 300 }}
source={{
uri: isAndroid
? 'file:///android_asset/widget/adSense.html'
: './widget/index.html',
}}
javaScriptEnabled={true}
mixedContentMode="compatibility"
injectedJavaScript={jsCode}
scrollEnabled={false}
domStorageEnabled={true}
onMessage={this._onMessage}
scalesPageToFit
startInLoadingState={true}
automaticallyAdjustContentInsets={false}
/>
;
</ScrollView>
);
}
}
虽然,我可以让它与这段代码一起工作,但 setTimeout 不是最好的解决方案:
window._googCsa('ads', pageOptions, adblock1);
var adSenseContainer = document.getElementById("afscontainer1");
setTimeout(function(){ window.postMessage(adSenseContainer.style.height, '*'); },1000);
你有什么想法吗?我认为我的函数 waitForAdSense() 可能会以某种方式被窃听。提前致谢!
【问题讨论】:
-
为什么使用 AdSense 而不是 AdMob?
-
此特定广告是 iframe,需要在 WebView 中实现。
-
那么这个特定的广告可能需要使用移动标准实施到移动设备上
标签: javascript react-native webview