首页 > 解决方案 > 如何使用 webview 获取最后更新的 HTML 内容?

问题描述

我有一个问题,我知道如何在 webview 中获取 HTML 源代码,并且有很多方法可以获取它。但这就是我遇到的:例如,我可以使用以下方法获取该网站的 html 源:

web.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');")

但它只是给了我第一个源代码 HTML,如果这个网站改变了 html 的某些元素或者内容会在几秒钟内改变,我无法得到它。那么如何在 webview 中获取最新的 html 呢?我正在使用 The Button,当网站更改内容时,我等待,我单击 Button 以获取 HTML,但仍然与第一次相同。谢谢

标签: javaandroidhtmlwebview

解决方案


您正在使用 javascript 来获取 html 代码,那么我认为您可以检测仍然使用 javascript的 html 更改。

您可以尝试使用 MutationObserver javascript 对象,https://developer.mozilla.org/it/docs/Web/API/MutationObserver

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
            //RELOAD YOUR WEBVIEW HERE
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
            //RELOAD YOUR WEBVIEW AND HERE
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

推荐阅读