问题
It seems I can't select DOM elements from a website I've loaded using the inAppBrowser plugin. When I log document.getElementById("input")
it's null
. The resources I've read on this have treated selecting elements as trivial, but I seem unable.
Here's the code I'm using:
var obj = {
link: "https://www.foolink.com",
input: "barInput",
func: function(obj) {
document.getElementById("input").value = obj.input;
}
}
var ref = cordova.InAppBrowser.open(obj.link, "_blank");
ref.addEventListener('loadstop', function() {
ref.executeScript({code:obj.func(obj)})
})
Has anyone else encountered this before? Using jquery to get selectors on gives me selectors from the index.html file, not the inAppBrowser window.
*edit: currently using inAppBrowser 1.4.0 and cordova 6.0.0
回答1:
Frix33 got the gears turning with his answer, but I don't think it specifically identifies the problem so posting my own. The script injected into the page must be a STRING or else it is just executed by the app, which is a different document
hence the null
result before. It works if you replace {code: obj.func(obj)}
with:
var codePass = "document.getElementById('input').value = '"+ obj.input +"';"
var ref = cordova.InAppBrowser.open(obj.link, "_blank", "location=yes");
ref.addEventListener('loadstop', function(event) {
ref.executeScript({code:codePass})
});
You can pass as many script lines as needed using that format.
回答2:
This work for me (cordova 6.1.1, inappbrowser 1.4.0, platform Android):
...
ref.addEventListener('loadstop', function () {
ref.executeScript(
{ code: "document.getElementById('inputID')" },
function (values) {
alert(values[0]);
}
);
...
来源:https://stackoverflow.com/questions/38086643/selecting-dom-elements-with-inappbrowser-cordova