首页 > 解决方案 > 使用 javascript 和 html 将搜索提交到外部网站并在新选项卡中打开

问题描述

我是社区的新手,但我期待随着我作为程序员的职业发展而增加价值。我有点卡住了,我希望能得到一些帮助。

我真的很接近做到这一点,但我有一个“#”让我失望。就是这种情况……

我正在构建的 chrome 扩展弹出窗口上有一个搜索框,旨在将其输入提交给另一个网站的搜索。例如,我进入我的搜索框“帮助”并按回车。

我去的网址是: https ://example.com/search/main.action/search/doAdvancedSearch.action?searchQuery.search=help

我需要去的网址是完全相同的,但在“main.action”之后我需要一个“#”。像这样: https ://example.com/search/main.action#/search/doAdvancedSearch.action?searchQuery.search=help

我的表单html代码如下:

<form target="_blank"  action="https://example.com/search/main.action/search/doAdvancedSearch.action" + "?">
<label>Search :
  <input type="search" name="searchQuery.search">
</label>
  <button type= "submit">Search website</button>
</form>

我的脚本如下:

var searchItem = document.getElementById('search').value;
console.log(searchItem);

function website(){
  window.open('https://example.com/home/main.action', '_blank');
  document.getElementById('q').value = searchItem;
  document.getElementById('searchArchived').click();
  var results = document.getElementById('search-results').value;
};

document.getElementById('gotowebsite').addEventListener('return', website);


}

我已经尝试了各种方法来在 url 中添加 # 但我没有任何运气。即使在 main.action 之后加上 + "#" 也会给我带来不想要的结果。有什么建议么?提前致谢。

是的,我尝试过使用针对类似问题的其他建议。他们没有解决 # 问题。:/

标签: javascripthtmlsearchexternalhashtag

解决方案


这可以完成工作:

function redirect() {
  var searchitem = document.getElementById("search");
  window.location.replace("https://example.com/search/main.action#/search/doAdvancedSearch.action?searchQuery.search" + searchitem.value);
}
<form action="javascript:redirect()">
  <label>Search :
  <input id="search" type="search">
</label>
  <button type="submit">Search website</button>
</form>

要在新选项卡中打开搜索页面:

function redirect() {
  var searchitem = document.getElementById("search");
  var url = "https://example.com/search/main.action#/search/doAdvancedSearch.action?searchQuery.search=" + searchitem.value;
  window.open(url,"");
}
<form action="javascript:redirect()">
  <label>Search :
  <input id="search" type="search">
</label>
  <button type="submit">Search website</button>
</form>


推荐阅读