Search code examples
javascripthtmlsearchexternalhashtag

Use javascript and html to submit a search to an external website and open in a new tab


I'm new to the community but I look forward to adding value as I grow in my career as a programmer. I'm a little stuck with something and I'm hoping I can get some help.

I'm really close to getting this right but I have one "#" that's throwing me off. This is the situation...

I have a search box on chrome extension pop-up I'm building that is meant to submit its input to the search of another website. Lets say for example I enter into my searchbox "help" and press enter.

The url I go to is this: https://example.com/search/main.action/search/doAdvancedSearch.action?searchQuery.search=help

The url I need to go to is the exact same thing but right after "main.action" I need a "#". Like this: https://example.com/search/main.action#/search/doAdvancedSearch.action?searchQuery.search=help

My html code for the form is as follows:

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

My script is as follows:

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);


}

I've tried all kinds of things to add the # in the url but I get no luck whatsoever. Even putting + "#" after main.action gives me unwanted results. Any suggestions? Thanks in advance.

And yes I've tried using the other suggestions that were given to similar questions. They didn't address the # problem. :/


Solution

  • This does the job:

    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>

    To open the search page in a new tab:

    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>