1

I am trying to make a chrome extension for an alternate new tab and am trying to make a search bar, The code that I have so far works alright but when I, let's say want to search "1+1" then instead of searching "1+1" it thinks that the "+" is a space and ends up searching "1 1" but does not give any errors.

HTML:

<input type="text" id="search-content"/>
<img id="search-submit" title="Search Google" src="search.png"/>

JS:

document.getElementById("search-submit").addEventListener("click", function() {
    if(!document.getElementById("search-content").value) return;
    let url = buildURL(document.getElementById("search-content").value);
    window.location.href = url;
});

function buildURL(string){
    string = string.split("");
    let url = "https://www.google.com/search?q=";
    for(let i = 0; i < string.length; i++){
        if(string.i === " ") return url = `${url}%20`
        url = `${url}${string[i]}`
        console.log(url);
    }
    return url
}

Manifest:

{
    "manifest_version": 2,
    "name": "New Tab",
    "description": "A New Tab",
    "version": "1",
    "permissions" : [
            "bookmarks",
        "storage",
        "sessions",
        "tabs"],
    "chrome_url_overrides" : {
        "newtab": "newpage.html"
    },
        "background": {
        "scripts":["background.js"],
    "persistent": false
    }
 }

This is my attempted fix at this however if(string.i === "+") does not seem to get called by the javascript even though it should. If anybody can suggest any other way to possibly do this it would be appreciated.

HTML:

<input type="text" id="search-content"/>
<img id="search-submit" title="Search Google" src="search.png"/>

JS:


document.getElementById("search-submit").addEventListener("click", function() {
    if(!document.getElementById("search-content").value) return;
    let url = buildURL(document.getElementById("search-content").value);
    window.location.href = url;
});

function buildURL(string){
    string = string.split("");
    let url = "https://www.google.com/search?q=";
    for(let i = 0; i < string.length; i++){
        if(string.i === " ") return url = `${url}%20`
        if(string.i === "+") return url = `${url}%2B`
        url = `${url}${string[i]}`
        console.log(url);
    }
    return url
}

Manifest:

{
    "manifest_version": 2,
    "name": "New Tab",
    "description": "A New Tab",
    "version": "1",
    "permissions" : [
            "bookmarks",
        "storage",
        "sessions",
        "tabs"],
    "chrome_url_overrides" : {
        "newtab": "newpage.html"
    },
        "background": {
        "scripts":["background.js"],
    "persistent": false
    }
 }

1 Answers1

0

I was able to use encodeURIComponent(<string>) in order to escape the special characters