在javascript中区分chrome浏览器和chrome应用程序

在javascript中区分chrome浏览器和chrome应用程序,javascript,google-chrome,google-chrome-app,user-agent,Javascript,Google Chrome,Google Chrome App,User Agent,如何区分我的代码是在chrome浏览器还是chrome应用程序中运行?该应用程序使用webview加载特定页面,其中javascript代码在chrome应用程序和chrome浏览器中的工作方式不同。最干净的方法是在加载页面之前进入webview 大致如下: webview.addContentScripts([{ name: 'beacon', matches: ['https://www.example.com/*'], js: { files: ['beacon.js'] },

如何区分我的代码是在chrome浏览器还是chrome应用程序中运行?该应用程序使用webview加载特定页面,其中javascript代码在chrome应用程序和chrome浏览器中的工作方式不同。

最干净的方法是在加载页面之前进入webview

大致如下:

webview.addContentScripts([{
  name: 'beacon',
  matches: ['https://www.example.com/*'],
  js: { files: ['beacon.js'] },
  run_at: 'document_start'
}]);
webview.src = "https://www.example.com/app"

// beacon.js
var script = document.createElement('script');
script.textContent = "window.inWebview = true;";
(document.head||document.documentElement).appendChild(script);
script.remove();
然后,在代码中,您可以检查
window.inWebview
是否已定义且为true

较不清洁的替代品:

  • 使用以可预测的方式修改用户代理
  • 只需加载带有额外参数的页面:
    https://www.example.com/app?webview=1

@Xan这不是复制品。这是关于网络视图中的代码。对了,抱歉,触发手指发痒。我要解开衣服。