Monday 4 January 2021

Cordova inAppBrowser Elements Returning Null

Cordova / Android

I am trying to load Amazon.com in Cordova's inAppBrowser and obtain an elements value, in this test I am trying to obtain the product title.

The element returns as null, I also put the code inside an interval to keep trying to access the element as perhaps it is still loading, but it still returns as null.

If I inject code where the user clicks a button I injected and that injected button runs the same element fetch code, then it will return with the correct value. But I want this done automatically.

Here is the code

function fetchTest() {
try {


var androidOptions =
  "location=no,hidden=yes,clearcache=yes,clearsessioncache=yes";

//test link
var url =
  "https://www.amazon.com/dp/B07L78Y72J";

inAppBrowserRef = cordova.InAppBrowser.open(
  encodeURI(url),
  "_blank",
  androidOptions
);

inAppBrowserRef.addEventListener("loadstop", loadStopCallBack);
inAppBrowserRef.addEventListener("loaderror", loadErrorCallBack);
inAppBrowserRef.addEventListener("message", messageCallBack);    

function loadStopCallBack() {
  if (inAppBrowserRef != undefined) {
    inAppBrowserRef.executeScript(
      {
        code:
          "setInterval(function(){ " + 
          "var item = ''; " +
          "try{ " +
          "item = document.getElementById('productTitle').innerHTML; " + 
          "} catch (err) { item = err.message; } " +
          "var messageObj = { my_message: item }; " +
          "var stringifiedMessageObj = JSON.stringify(messageObj); " +
          "webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj); " +
          "}, 3000);",
      },
      function () {
        //alert("inject finished");
      }
    );
  }
}

function loadErrorCallBack(params) {
  alert("load error: " + params.message);
}

function messageCallBack(params) {
  alert("message [" + params.data.my_message + "]");
}
} catch (err) {
  alert("fetchTest: " + err.message);
}
}

I know there are other means to obtain this data, but I would like to obtain it using Cordova's inAppBrowser.

Any thoughts?

Thanks

This question addresses the problem, but the proposed solution does not work for me Selecting DOM elements with inAppBrowser - Cordova



from Cordova inAppBrowser Elements Returning Null

No comments:

Post a Comment