在以下脚本中,一旦按下按钮,就会打开一个新的Google浏览器标签。然后,我想在这个新打开的标签上填写搜索框。
如何将焦点切换到这个新标签,以便我可以等待它完全加载然后填充搜索框?
<button id="start">Google</button>
<script>
function open_google_in_new_tab() {
var url = "https://www.google.com";
window.open(url);
window.onload(fill_search_box()); // here it will try to operate on the old tab
};
function fill_search_box() {
var search_box = document.getElementsByName("q")[0];
search_box.value = "Some text";
};
var start_button = document.getElementById("start");
start_button.addEventListener("click", open_google_in_new_tab);
</script>
答案 0 :(得分:1)
您无法从脚本中准确定位另一个文档中的另一个元素,但是,您可以使用查询字符串设置Google文本框的文本框值:
www.google.com?q=SearchTerm
在创建SearchTerm时,您还应该使用encodeURI
来确保您附加的搜索查询符合URL标准
此外,如果您希望在另一个标签中打开窗口,则可以使用window.open(url, "_blank")
打开。
请参见以下示例:
注意:-由于摘要限制,该页面无法打开-请在您自己的浏览器中运行。
<button id="start">Google</button>
<script>
function open_google_in_new_tab() {
var text = "Some text";
var url = "https://www.google.com?q=" + encodeURI(text);
console.log(url)
window.open(url, '_blank');
};
var start_button = document.getElementById("start");
start_button.addEventListener("click", open_google_in_new_tab);
</script>
答案 1 :(得分:0)
不幸的是,您不能使用Javascript做到这一点。
但是,如果您愿意尝试的话,这可能会使您取得类似的成就。
您可以通过Google网站查询字符串中名为“ q”的参数来操纵搜索字符串。因此,为了使用户能够使用Google搜索特定的单词,请将关键字附加到该单词上。像这样:
ServiceCollectionServiceExtensions.AddScoped