获取新打开和加载的元素 window - Javascript

Get element of a newly opened & loaded window - Javascript

在 Twitter 帐户页面上(比方说 Whosebug:https://twitter.com/Whosebug),我正在尝试获取该帐户的用户名,然后打开一个新的 window 查询该帐户的用户名google 搜索。最后想获取新打开标签页的查询文本

为此,我执行了以下操作:

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 的.

我知道这是回调的问题,await/async,我已经阅读了很多关于它的内容,但这些主题让我感到困惑。

只需将 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 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 试过你的场景:分享下面的片段: