我正在寻找一种方法来控制文档中的元素。问题是,该文档附加到iFrame。
以下是一个例子:
// You need to make sure that the button element exists before trying to attach a click handler to it.
// You can do that by running the function when the onload event is triggered.
window.onload = function () {
var acc;
acc = document.getElementsByClassName('button')[0];
// You have errors in the above line, "s" is missing in getElement/s/ByClassName, also that method returns an array, not an element, so you need to add [0] at the end.
acc.onclick = function()
{
this.classList.toggle("active");
// this.nextElementSibling.classList.toggle("show");
// This does not work because <button> is in <center> and the panel div is therefore not its sibling.
// there are many ways to reference the panel div, eg:
var panel= document.getElementsByClassName("panel")[0];
panel.classList.toggle("show");
}
}
我上面要做的是:
答案 0 :(得分:2)
我遇到了类似的问题。由于某种原因(Windows?已过时?),nightmare-iframe
包对我不起作用。
所以我使用纯DOM做了这个,它会转录给你:
var info = {
"account": account_number,
"security": testData.security_code;
};
nightmare.wait( () => {
/* Return true when the iframe is loaded */
var iframe = document.querySelector("iframe[name='wc']");
if (!iframe) {
return false;
}
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
return iframeDocument.querySelector("#account_number") != null;
}).evaluate( (info) => {
var iframe = document.querySelector("iframe[name='wc']");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.querySelector("#account_number").value = info.account;
iframeDocument.querySelector("#card_security_code").value = info.security;
//also use DOM to set proper date
...
iframeDocument.querySelector("span#hpp-form-submit").click();
}, info).then( () => {
console.log("submit done!");
}).catch((error) => {
console.error("Error in iframe magic", error);
});
这仅适用于iframe与主页位于同一域中,iframe允许same-origin的情况。我的用例是从商家页面登录到paypal。
对于具有不同来源的iframe,nightmare-iframe
将是要使用的包,但是需要一个错误来查看问题所在。