2017-02-19 346 views
1

我想要一个谷歌浏览器扩展功能,可以向用户发出一个单词并在亚马逊网站上进行搜索,并在用户的单个HTML页面上显示搜索结果。如何使用谷歌浏览器扩展搜索亚马逊?

我尝试用JavaScript和DOM,这是我的代码:

manifest.json的:

{ 
    "manifest_version": 2, 

    "name": "Amazon Search", 
    "description": "This extension to sarch from Amazon.com", 
    "version": "0.1", 

    "browser_action": { 
    "default_icon": "amazon.png", 
    "default_popup": "form.html" 
    }, 
    "background": 
    { 
    "scripts": ["search.js"] 
    }, 
    "permissions": [ 
    "activeTab", 
    "tabs", 
    "https://ajax.googleapis.com/", 
    "https://amazon.com/" 
    ] 
} 

form.html:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>Form</title> 
    <script src="search.js"></script> 
</head> 
<body> 
    <form> 
     <label>Search : </label><input type="text" id="search" /> 

     <button id="gotoamazon" >Search Amazon</button> 

    </form> 

</body> 
</html> 

search.js:

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

    function amazon(){ 
     window.open('https://amazon.com','_blank'); 
     document.getElementById('twotabsearchtextbox').value = searchItem; 
     document.getElementById('nav-search-submit-text').click(); 
     var results = document.getElementById('resultsCol').value; 
    }; 

    document.getElementById('gotoamazon').addEventListener('click', amazon); 

我有一些麻烦,如何在另一个页面上显示搜索结果(结果变量)?

回答

1
  1. 不要在不同的页面中包含相同的DOM脚本,因为背景页面是不同的上下文。必读:extensions architecture

  2. 右击扩展弹出窗口并选择检查打开devtools为弹出:你会看到在控制台选项卡中的错误:<script src="search.js"></script>同步执行的脚本,这意味着没有什么在身体又那么你的代码将无法获得元件。在关闭</body>标记之前使用DOMContentLoaded事件或移动脚本标记。

  3. 由于您不想直接访问它,因此无需获得亚马逊的许可。
    不需要背景页脚本。

此任务可以不用脚本来解决:

  1. 无需手动打开的窗口,只需要使用提交到_blank形式和亚马逊的搜索URL,其您可以从网站上的实际搜索结果页面进行复制(可选择删除跟踪/辅助参数):https://www.amazon.com/s/?field-keywords=derp

  2. 使用<button type="submit">

  3. 使用type="search"input提供自动完成历史和x按钮清除场。

  4. input放在label里面 - 这样你也可以点击标签来关注输入。

<html> 
<head> 
    <title>Form</title> 
</head> 
<body> 
    <form target="_blank" action="https://www.amazon.com/s/"> 
     <label>Search : 
      <input type="search" name="field-keywords"> 
     </label> 
     <button type="submit">Search Amazon</button> 
    </form> 
</body> 
</html> 

这将打开与亚马逊寻找新的前景标签。如果您需要背景选项卡,则需要脚本,并且应该使用chrome.tabs.create({url: newUrl, active: false})