簡體   English   中英

獲取新打開和加載的元素 window - Javascript

[英]Get element of a newly opened & loaded window - Javascript

在 twitter 帳戶頁面上(假設 StackOverflow: https://twitter.com/stackoverflow ),我試圖獲取該帳戶的用戶名,然后打開一個新的 Z05B8C74CBD96FBF2DE4ZC1A 上的用戶名搜索帳戶。 最后,我想獲取新打開的選項卡的查詢文本。

為此,我執行了以下操作:

function getUserName(callback) {
  url = window.location.href;
  console.log(url);
  sn = url.split("/").slice(-1)[0];
  console.log(sn);
  window.location.href = `https://google.com/search?q=${sn}`;
  callback();
};

function getQuery() {
  console.log(window.location.href);
}

getUserName(getQuery);

問題是它不會等待新頁面被加載,因此 console.log() 表單 getQuery() 是 twitter 的,而不是 google 的。

我知道這是回調和等待/異步的問題,我已經閱讀了很多關於它的內容,但這些主題讓我感到困惑。

只需將https://google.com/search?q=${sn}傳遞給全局變量並使用它。

像這樣:

let windowHref = window.location.href;

function getUserName(callback) {
  url = window.location.href;
  console.log(url);
  sn = url.split("/").slice(-1)[0];
  console.log(sn);

  windowHref = `https://google.com/search?q=${sn}`;
  window.location.href = windowHref;
  callback();
};

function getQuery() {
  console.log(windowHref);
}

getUserName(getQuery);

至於獲取query text of the newly opened tab 您需要在getUserName() function 中使用回調 function。

function getUserName(callback) {
  url = window.location.href;
  console.log(url);
  sn = url.split("/").slice(-1)[0];
  console.log(sn);

  windowHref = `https://google.com/search?q=${sn}`;
  callback(windowHref); // Sending back the url to the callback as parameter
};

function getQuery(queryText) { // Value returned from the callback.
  console.log(queryText);
}

getUserName(getQuery);

我用linkedin嘗試了你的場景:分享下面的片段:

進行函數調用

找回價值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM