簡體   English   中英

getElementsByTagName 不能與 Cordova 中的 InAppBrowser 一起使用

[英]getElementsByTagName not working with InAppBrowser in Cordova

我們的網站已加載到我們的 Cordova 應用程序的 InAppBrowser 中,我正在嘗試使用這樣的 executeScript 獲取所有鏈接標簽:

  getAllLinks() {
    inappbrowser.executeScript({
        code: "(function(){ \
            return document.getElementsByTagName('a'); \
        })();"
    },function(values){
        console.log("length values = " + values.length); // length is always 1
        for(var x=0; x < values.length; x++) {
          var href = values[x].href;
          console.log("href = " + href);
        }
    });
  }

// loadstop_handler:
loadstop_handler(evt: InAppBrowserEvent) {
    if (device.platform == "Android") {
      this.getAllLinks();
    }
}

// loadstop handler is added to event listener:
inappbrowser.addEventListener('loadstop', (event) => this.loadstop_handler(event));

但是我沒有得到鏈接。 它返回一個空的 object 並且 href 始終未定義。 打開應用程序時,主頁上大約有 10 個鏈接。 我在 loadstop 事件中調用此方法。 我們正在使用 Cordova 8.1.0 有人可以幫忙嗎? 我怎樣才能得到鏈接?

編輯

根據此鏈接似乎: https://dbwriteups.wordpress.com/2016/01/24/sharing-data-between-hybrid-app-and-inapp-browser/您無法訪問該網站的DOM在 InAppBrowser 中加載。 這是一個不同的背景。 這就是為什么 document.getElementByTagName 在 executeScript 中返回 undefined 的原因。

所以我應用了上述鏈接提供的解決方案。 這並不理想,因為我必須從網站在本地存儲中設置數據(如:在網站代碼本身中),如下所示:

// Code executed in website:
setLocalStorageForApp() {
    setTimeout(() => {  // waiting for DOM to load
      let links = document.getElementsByTagName('a');
      var linkArray = new Array<string>();
      for (var x = 0; x < links.length; x++) {
        var href = links.item(x).href;
        linkArray.push(href);
      }
      console.log('Total links = ' + linkArray.length); // result is 63
      localStorage.setItem('linkArray', JSON.stringify(linkArray));
    }, 1000);
  }

然后在 Cordova 應用程序中,我可以從本地存儲中獲取 a 標簽:

var links = null;
inappbrowser.executeScript({ code: "localStorage.getItem('linkArray')" }, function(values) {
  links = JSON.parse(values[0]);
  console.log(links); // prints all 63 links from web page
});

因此,您無法從應用程序訪問在 InAppBrowser 中加載的網站的上下文。 共享數據(顯然包括“文檔”)的唯一方法是通過本地存儲。 如果我有這個錯誤或有人知道不需要我修改網站本身代碼的更好的解決方案,請告訴我。 我已經嘗試了一切,試圖從網站的 DOM 中獲取元素,但一切都失敗了。

返回參數始終包裝在單個元素數組中。 嘗試這個:

getAllLinks() {
    inappbrowser.executeScript({
        code: "(function(){ \
            return document.getElementsByTagName('a'); \
        })();"
    },function(values){
        values = values[0]; // destructure single element array
        console.log("length values = " + values.length);
        for(var x=0; x < values.length; x++) {
          var href = values[x].href;
          console.log("href = " + href);
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM