gpt4 book ai didi

安卓 WebView : Scripts may close only the windows that were opened by it

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:35 29 4
gpt4 key购买 nike

我正在加载一个特定的 url

例如。

webview.loadUrl("some.domain.com")

后记我将它重定向到其他域,然后返回到我的域。然后我尝试在我的 javascript (window.close()) 中关闭窗口。在 chrome 开发者工具上远程调试时出现以下错误

Scripts may close only the windows that were opened by it.

即使我在打开它的同一个域中,我也会收到上述错误。

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

这个答案将从 Android 应用开发者的角度出发。我希望它会对某人有所帮助。

这个问题对我来说非常相似:我通过 webview 打开一个网站,一些链接在新窗口中打开。问题是 webview 不能开箱即用地使用 web 窗口。我的意思是,这是可能的,但不像预期的那样(在我的例子中,当从 javascript 的角度在一个单独的窗口中打开一个链接时,它会覆盖以前打开的页面,并且不能用 window.close( ) 来自 javascript,最终导致前一页的状态丢失)。

所以我的任务是在一个窗口中打开一个链接并返回到上一页而不会丢失任何状态。那是我的解决方案。我有两个单独的 WebView - 一个作为主视图,另一个用于窗口中的链接。为了能够对“新窗口中的链接”事件使用react,我将使用以下代码配置主 webView:

    webView.settings.javaScriptEnabled = true
webView.settings.javaScriptCanOpenWindowsAutomatically = true
webView.settings.setSupportMultipleWindows(true)

webView.webChromeClient = object : WebChromeClient() {

override fun onCreateWindow(view: WebView?, isDialog: Boolean, isUserGesture: Boolean,
resultMsg: Message?): Boolean {
handleCreateWebWindowRequest(resultMsg)
return true
}
}

我们只需要 onCreateWindow 回调来覆盖主 webView chrome 客户端,因为它只会打开新窗口。并且还允许在 webView.settings 中支持多窗口。当 onCreateWindow 回调触发时,执行以下操作:

@SuppressLint("SetJavaScriptEnabled")
override fun handleCreateWebWindowRequest(resultMsg: Message?) {
if (resultMsg == null) return
if (resultMsg.obj != null && resultMsg.obj is WebView.WebViewTransport)
{
val transport = resultMsg.obj as WebView.WebViewTransport
windowWebView = WebView(this)
windowWebView?.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)

windowWebView?.settings?.javaScriptEnabled = true
windowWebView?.settings?.javaScriptCanOpenWindowsAutomatically = true
windowWebView?.settings?.setSupportMultipleWindows(true)
windowWebView?.webViewClient = WebViewClient()
windowWebView?.webChromeClient = object : WebChromeClient() {
override fun onCloseWindow(window: WebView?) {
super.onCloseWindow(window)
handleCloseWebWindowRequest()
}
}

container.addView(windowWebView)
webView.visibility = View.GONE
transport.webView = windowWebView
resultMsg.sendToTarget()
}
}

基本上我们将这个(创建窗口)请求发送到一个单独的 webView。在其中我们还应该允许多窗口支持并附加一个 chrome 客户端,我们应该只监听 onCloseWindow 事件,因为这个 webView 应该表现为一个窗口。当 onCloseWindow 触发时,我们只是关闭(隐藏/删除)应该充当窗口的 webView,然后返回到主窗口。这里的 isWebWindowOpened 方法调用只是检查 windowWebView 是否不为空且可见。

private fun handleCloseWebWindowRequest() {
if (!isWebWindowOpened()) return

container.removeView(windowWebView)
webView.visibility = View.VISIBLE
windowWebView = null
}

我唯一可以提及的是,当 windowWebView 打开时,onBackPressed 操作应该调用 handleCloseWebWindowRequest 关闭它。

关于安卓 WebView : Scripts may close only the windows that were opened by it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48989427/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com