![](/img/trans.png)
[英]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.