How to detect in JavaScript if a page was loaded in a Chrome webview?

吃可爱长大的小学妹 提交于 2019-12-22 06:08:12

问题


I'm writing a packaged app for Chrome that has a webview tag where I load my website.

Is it possible for the website JavaScript code to detect that it was loaded in a webview? The navigator.userAgent property has no clues.


回答1:


Other approaches in addition to the one mentioned by Jivings:

  • Load a slightly different URL in the webview, e.g., http://example.com?in_webview=1, and reflect that in the JavaScript served by the site.
  • Same idea but use a #fragment. I don't know for sure whether a #fragment will work correctly, but it if does, it's nice because the server won't get confused by a strange query param.
  • Using the embedder, insert a script into the webview's DOM that does something different.



回答2:


When the webview has finished loading fire an event to the page inside:

webview.addEventListener("loadstop", function () {
   contentWindow.postMessage('Hello from Chrome App!', targetOrigin)
});

Your content page can listen for this message using the regular postMessage API. If it receives a message you will know it is loaded in a webview.



来源:https://stackoverflow.com/questions/17253997/how-to-detect-in-javascript-if-a-page-was-loaded-in-a-chrome-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!