gpt4 book ai didi

javascript - 如何创建 chrome 扩展来打开由用户输入生成的特定网址?

转载 作者:行者123 更新时间:2023-12-03 09:01:22 25 4
gpt4 key购买 nike

我想制作 chrome 扩展,它可以打开从用户输入生成的特定网址。用户输入一两个单词,然后当用户点击提交按钮时,用户将被重定向到“hxxps://webaddress.com/input1”或“hxxps://webaddress.com/input2”或“hxxps://webaddress.com/input1/input2”。

这是我的 popup.html 代码,

<!DOCTYPE html>

<html>
<body style="width: 300px">
<div>input1:<input type="text" id="input1"></input></div>
<div>input2:<input type="text" id="input2"></input></div>
<button id="submit">submit</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>

这是我的 popup.js,

document.getElementById('submit').addEventListener('click',function(){
var input1= document.getElementById('input1').value;
var input2= document.getElementById('input1').value;
chrome.tabs.update(tab.id, {url: "https://webaddress.com/"+input1+"/"+input2});
});

但是它不起作用。有人可以帮助我让它发挥作用吗?感谢您的帮助。

最佳答案

您需要更加小心您的代码。

var input1= document.getElementById('input1').value;
var input2= document.getElementById('input1').value; // input1 again? Copy-paste error

还有:

// tab.id? What's that? Where is it defined? And as such, this produces an exception:
chrome.tabs.update(tab.id, {url: "https://webaddress.com/"+input1+"/"+input2});
<小时/>
  1. 首先,学习如何调试代码。甚至还有a tutorial in the docs 。因此,如果发生完全停止执行的异常(如您的情况),您将了解它并了解一些有关它的详细信息。

  2. 接下来,请阅读 documentation of the functions you use :

    chrome.tabs.update(integer tabId, object updateProperties, function callback)

    Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified.

    integer (optional) tabId
    Defaults to the selected tab of the current window.

    您可能正在尝试更新当前选项卡;在这种情况下,您根本不需要提供 tabId (它被标记为可选):

    chrome.tabs.update({url: "https://webaddress.com/"+input1+"/"+input2});
  3. 编码时要小心。有一种东西叫rubber duck debugging ,当你假装向其他人解释你的代码时,逐行:“这行应该做 X” 等。你会这样捕获第一个错误。当然,测试也是必要的。

  4. 作为一名程序员,你必须思考 edge cases 。如果 input1 为空怎么办?它将变成 "https://webaddress.com//something",这不好。您需要添加逻辑来防止这种情况发生。 这是留给读者的练习。

  5. 您还应该考虑用户体验。如果您只是覆盖当前选项卡,用户会喜欢吗?有时这就是重点,但更常见的是不打开新选项卡更好。因此,您需要改用 chrome.tabs.create(同样,适用第 2 步 - 阅读文档)。

关于javascript - 如何创建 chrome 扩展来打开由用户输入生成的特定网址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32293663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com