从Cordova获取网站的源代码(内容)

时间:2017-08-21 16:01:21

标签: cordova http httprequest cordova-plugins http-get

当我遇到一个小问题时,我正在创建一个cordova混合应用程序:我需要从应用程序中获取外部网站的内容。

为了更清楚,我将详细解释:我有一个cordova应用程序,我需要获取外部网站源代码并将其输出到div tag:与PHP file_get_contents完全一样。

我使用该代码实现了jQuery(我不想使用):

var request = $.ajax({
    url: 'http://www.example.com/',
    type: 'GET',
    crossDomain: true,
    async:false,
    success: function(res) {
        var el = document.createElement('html');
        el.innerHTML = res;
        document.getElementById("anID").innerHTML = el;
    }
});

但是我不想使用该解决方案有几个原因:

  1. 内容需要很长时间才能显示
  2. 它有时会使应用程序崩溃
  3. 所以我的问题是:这可以以更有效的方式制作吗?也许使用在后台加载内容的插件可以解决这个问题?我需要将JS应用于此内容,因此我不想使用iframe或inAppBrowser

    在Google和StackOverflow上搜索没有找到任何内容后我问了这个问题

    更新

    我发现这个插件发出了HTTP请求,但我不确定如何在这种情况下使用它:https://github.com/wymsee/cordova-HTTP

    我正在使用此代码,但它什么都不做:

    document.addEventListener("deviceready", function() {
        window.cordovaHTTP.get("http://www.lycee-tripoli.edu.lb/",
        {},
        {},
        function(response) {
            alert(response.status);
        },
        function(response) {
            alert(response.error);
        });
    }, false);
    

    此代码应提醒响应,我从README.md文件中复制了该代码。它实际上完全没有没有,甚至没有错误。我做错了吗?

    感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

这是一个小修改 - 但我不建议 - :

var request = $.ajax({
  url: 'https://microsmsm.com/',
  type: 'GET',
  crossDomain: true,
  async: true,
  success: function(res) {
    $("html").html(res);
    //do modifications to html here
  }
});

答案 1 :(得分:0)

你可以在vanilla Javascript中执行此操作:

const changeHTMLContent = () => {
    const url = "https://microsmsm.com"
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            console.log(xhr.responseText)
            document.open();
            document.write(xhr.responseText)
            document.close();
        }
    }
    xhr.send();
}

changeHTMLContent();