안드로이드 스튜디오
[안드로이드 스튜디오 코틀린] WebView Header 추가하기
권송미
2024. 2. 21. 12:00
728x90
반응형
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var webView : WebView
private val header = mutableMapOf<String, String>()
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
webView = binding.webView
webView.apply {
webChromeClient = WebChromeClient()
webViewClient = WebViewClient()
settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true // window.open() 동작 허용
loadsImagesAutomatically = true
domStorageEnabled = false
setSupportZoom(false)
builtInZoomControls = false
displayZoomControls = false
setSupportMultipleWindows(true)
}
}
header[HEADER_NAME] = HEADER_VALUE
// webViewClient가 웹 페이지가 로드하는 동안 요청을 가로채고 제어할 수 있기 때문에 loadUrl과 같이 사용함
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
request?.let {
view?.loadUrl(it.url.toString(), header)
return true
}
return super.shouldOverrideUrlLoading(view, request)
}
}
webView.loadUrl(WEBVIEW_URL, header)
}
companion object {
private const val WEBVIEW_URL = "https://www.naver.com/"
private const val HEADER_NAME = "headerName"
private const val HEADER_VALUE = "headerValue"
}
}
728x90
반응형