获取新打开的&;已加载的窗口-Javascript
在twitter帐户的页面上(比如StackOverflow:),我试图获取帐户的用户名,然后在google搜索中打开一个新窗口查询帐户的用户名。最后,我想获取新打开的选项卡的查询文本 为此,我做了以下工作:获取新打开的&;已加载的窗口-Javascript,javascript,async-await,callback,Javascript,Async Await,Callback,在twitter帐户的页面上(比如StackOverflow:),我试图获取帐户的用户名,然后在google搜索中打开一个新窗口查询帐户的用户名。最后,我想获取新打开的选项卡的查询文本 为此,我做了以下工作: function getUserName(callback) { url = window.location.href; console.log(url); sn = url.split("/").slice(-1)[0]; console.log(sn
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()form 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);
至于获取新打开选项卡的
查询文本
。您需要在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尝试了你的场景:分享下面的片段:
非常感谢@imran rafiq。当我复制粘贴代码时,它会获得查询搜索,但不会打开新选项卡。