[英]How can I load scripts after the window.onload event with reactjs / nextjs
[英]How can I run code after webpage has loaded in JS (window.onload is failing me)?
嘿嘿,
我正在尝试创建一个脚本来打开 URL 并使用给定的凭据登录。
因此我创建了这个:
window.open("https://stackoverflow.com/users/login");
document.getElementById('email').value = "ThisIsMy@Email.com";
document.getElementById('password').value = "ThisIsMyPassword";
document.getElementById('submit-button').click();
但后来我更改了代码以使用window.onload
等待页面加载:
window.open("https://stackoverflow.com/users/login");
window.onload = function() {
document.getElementById('email').value = "ThisIsMy@Email.com";
document.getElementById('password').value = "ThisIsMyPassword";
document.getElementById('submit-button').click();
}
但是,这似乎不起作用。
因此,我在代码中添加了一些console.log
进行调试,如下所示:
console.log("starting")
window.open("https://stackoverflow.com/users/login");
console.log("page open")
window.onload = function() {
console.log("page loaded")
document.getElementById('email').value = "ThisIsMy@Email.com";
document.getElementById('password').value = "ThisIsMyPassword";
document.getElementById('submit-button').click();
console.log("signed in")
}
当我在控制台(Chrome/Firefox)中运行代码时,我重新started
并page open
,但没有别的。 当我测试隔离的 function (即 3 个不同的document.getElementById
)时,它工作得很好。 window.onload
调用一定有问题?
从 StackOverflow 上的其他来源,我尝试改用document.onload
,我也尝试使用document.addEventListener('DOMContentLoaded', function() {...}
,但这些似乎都不起作用。
有没有人有什么建议?
#新手
您根本无法访问跨源页面。 您正在尝试的内容仅适用于浏览器插件。 插件还需要用户授予的特定权限。 例如修改webRequest的chrome权限: https://developer.chrome.com/docs/extensions/reference/webRequest/
window.open()
返回子 window 如果它是about:blank
或者如果应用同源规则(协议、主机名和端口 - 见下图),则可以访问它。 看看这个小提琴它显示的东西类似于你正在尝试的东西。 (CORS 1)
在这里,您可以看到您可以访问哪个子 windows。 这意味着即时修改它或完全覆盖它的内容/位置。
在两个页面之间进行通信的唯一方法是: window.postMessage()
和window: Message-Event
,它提供了一个易于使用的 API 进行通信。
在您的 html 页面中,在您调用 js 页面的script
标记中,添加defer
。 像这样:
<script src="your_script.js" defer></script>
我想提醒您,在 javascript 中使用密码凭证不是一个好主意,因为它很难防止公开露面。
I believe you can solve this kind of problem with programs such as Python, C++, maybe Java, but Javascript is a Client-Side program which has some limitations but if you ask me these limitations actually makes it quite fun to use most of the time .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.