[英]Find <video> tag in newly opened window in Javascript
我想循環瀏覽鏈接列表並在新的 window 中打開每個鏈接,並在每個鏈接中獲取標簽。
到目前為止,我已經實現了這一點:
for(var i = 0; i < links.length; i++) {
console.log(links[i]);
var openedWindow = window.open(links[i], '_blank').focus();
videoList.push(openedWindow.document.querySelectorAll("div video")); //Add the video links in the newly opened video
openedWindow.close();
}
videoList 是一個全局變量
const videoList = [];
每當我嘗試在 Chrome 中運行此代碼時都會遇到錯誤
Uncaught TypeError: Cannot read properties of undefined (reading 'document')
at grabLinks (<anonymous>:15:45)
at <anonymous>:69:1
錯誤在這行代碼中:
videoList.push(openedWindow.document.querySelectorAll("div video"));
我的問題是我到底做錯了什么,我該如何解決?
如果您需要更多信息,請告訴我。
由於鏈接與您運行它的頁面位於同一來源,因此您應該能夠訪問文檔的內容 - 但您必須等待這些內容加載,而您當前的代碼沒有這樣做。 這涉及等待來自openedWindow
的事件,這意味着整個過程將是異步的。
另外,您當前的代碼正在抓取video
元素,但是您正在關閉這些video
元素所在的 window。這可能沒問題,但是從名稱grabLinks
聽起來您主要對currentSrc
或src
感興趣video
元素,所以讓我們抓住它。
我會寫一個 function 來做一個 window,可能會返回一個 promise:
function getVideoSources(link) {
return new Promise((resolve, reject) => {
const openedWindow = window.open(link, "_blank");
openedWindow.focus();
openedWindow.addEventListener("DOMContentLoaded", () => {
try {
const videoElements = openedWindow.document.querySelectorAll("div video");
const sources = Array.from(videoElements, element => element.currentSrc || element.src);
resolve(sources);
} catch (e) {
reject(e);
} finally {
try {
openedWindow.close();
} catch (e2) { } // In an up-to-date browser, you can leave
// the `(e2)` part off
}
});
});
}
然后grabLinks
可以是一個async
的function,它通過一系列的URL工作(因為瀏覽器不會讓你一次打開一堆windows,並且focus()
調用會相互干擾):
async function grabLinks(links) {
const videoList = [];
for (const link of links) {
const sources = await getVideoSources(link);
videoList.push(...sources);
}
return videoList;
}
GrabLinks 中grabLinks
的實現值將是元素中currentSrc
或src
屬性值的數組。
但請注意,這需要通過用戶操作(按鈕單擊或類似操作)啟動,並且瀏覽器可能會限制您可以連續打開多少個 windows。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.