【问题标题】:Get element of a newly opened & loaded window - Javascript获取新打开和加载的窗口的元素 - Javascript
【发布时间】:2021-04-24 00:51:32
【问题描述】:

在 twitter 帐户页面上(比如说 StackOverflow:https://twitter.com/stackoverflow),我试图获取该帐户的用户名,然后打开一个新窗口,在 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 的。

我知道这是一个回调和等待/异步的问题,我已经阅读了很多关于它的内容,但这些主题让我感到困惑。

【问题讨论】:

    标签: javascript async-await callback


    【解决方案1】:

    至于获得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尝试了你的场景:分享下面的sn-ps:

    【讨论】:

    • 谢谢@imran-rafiq-rather。当我复制粘贴您的代码时,它会获取查询搜索,但不会打开新标签。
    【解决方案2】:

    只需将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);
    

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 2022-09-28
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多