๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป๊ฐœ๋ฐœ

JavaScript์—์„œ alert()์„ ์‚ฌ์šฉํ•  ๋•Œ Android WebView์—์„œ ํƒ€์ดํ‹€ ์—†์ด ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ๋ฒ•

by ๋ˆˆ๋ˆ„ :) 2023. 3. 28.

 

JavaScript์—์„œ alert() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ Android WebView์—์„œ ํƒ€์ดํ‹€ ์—†์ด ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ๋ฒ•

 

 

 

WebChromeClient ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ onJsAlert() ๋ฉ”์„œ๋“œ๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋“œํ•˜๊ณ  alert ์ฐฝ์„ ์ปค์Šคํ„ฐ๋งˆ์ด์ง•ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext())
                .setMessage(message)
                .setPositiveButton(android.R.string.ok, null);
        builder.show();
        // ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ•œ ํ›„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
        result.confirm();
        return true;
    }
});

 

 

 

์œ„์˜ onJsAlert() ๋ฉ”์„œ๋“œ์—์„œ๋Š” ํƒ€์ดํ‹€ ์—†์ด JavaScript alert ์ฐฝ์˜ ๋‚ด์šฉ๋งŒ์„ ์ถœ๋ ฅํ•˜๋Š” ์ปค์Šคํ…€ AlertDialog๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค.

๊ฒฐ๊ณผ๋ฅผ ์ฒ˜๋ฆฌํ•  ๋•Œ, result.confirm() ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ํด๋ผ์ด์–ธํŠธ๊ฐ€ alert ์ฐฝ์„ ์ฒ˜๋ฆฌํ•  ๊ฒƒ์ž„์„ ์•Œ๋ฆฌ๊ณ ,

๋งˆ์ง€๋ง‰์œผ๋กœ true๋ฅผ ๋ฐ˜ํ™˜ํ•˜์—ฌ ํด๋ผ์ด์–ธํŠธ๊ฐ€ alert ์ฐฝ์„ ์ฒ˜๋ฆฌํ•  ๊ฒƒ์ž„์„ ์•Œ๋ฆฝ๋‹ˆ๋‹ค.

์ด ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋“œ๋กœ์ด๋“œ WebView์—์„œ JavaScript alert ์ฐฝ์ด ์‹คํ–‰๋  ๋•Œ, ํƒ€์ดํ‹€ ์—†์ด ๋‚ด์šฉ๋งŒ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.