锚标签内的 Chrome Extensiom 提交按钮不会重定向

问题描述

我正在构建一个简单的 chrome 扩展。在其中,我试图让表单中的提交按钮在提交表单后将用户重定向到不同的页面,但我无法让它工作。我尝试了以下方法

//First way
const button = document.querySelector('.button');
button.addEventListener('click',() => {
    document.location.href = 'results.html';
});

//Second way
const form = document.querySelector('form');
form.onsubmit = redirect;

function redirect() {
    location.href = 'results.html';
    console.log("successfully redirected");
};

//Third way
<button onclick="window.location.href='results.html'" class="button" type="submit">Submit</button>

//Fourth way
<a href="results.html">
    <button class="button" type="submit">Submit</button>
</a>

我的表格是这样的

<form method="POST" action="http://localhost:3000/sleep">
    <label> How much did you sleep last night?
      <input name="duration" type="number">
    </label>
    <label> How well did you sleep?
      <div>
        <label>
          <input type="radio" name="quality" value="bad">
          Bad
        </label>
        <label>
          <input type="radio" name="quality" value="ok">
          Ok
        </label>
        <label>
          <input type="radio" name="quality" value="good">
          Good
        </label>
      </div>
    </label>
    <input type="hidden" name="user_id" value="1">
    <button class="button" type="submit">Submit</button>
</form>

我尝试使用提交按钮以外的其他元素重定向一个页面,并且以某种方式起作用。是否有关于提交按钮的内容不允许我重定向?我试图通过在表单提交后立即重定向来改善用户体验,因此如果可能的话,我想使用提交按钮进行重定向。另外,我不知道这是否相关,但我使用的是 manifest v3。

解决方法

这样使用

function clickHandler(e) {
    chrome.tabs.update({url: "https://stackoverflow.com"});
    window.close(); // Note: window.close(),not this.close()
}
document.addEventListener('DOMContentLoaded',function() {
    document.getElementById('button').addEventListener('click',clickHandler);
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...