且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome扩展程序sendResponse无法正常工作

更新时间:2023-12-05 18:55:34

用户wOxxOm在其评论中提供了此答案.

User wOxxOm provided this answer in his comments.

在popup.js示例中,我将附加到表单"onsubmit"事件以触发我的代码.

In the popup.js example, I am attaching to the form 'onsubmit' event to trigger my code.

我以前读过,如果关闭弹出窗口,它将不再有代码可以运行.正如wOxxOm所指出的,我无法直观地看出我的情况是Submit事件重新加载了弹出窗口.那是断开我的代码.

I had previously read that if the popup gets closed, it's code would no longer be there to be run. I could not visually tell in my case that, as wOxxOm pointed out, that the submit event reloads the popup. That was disconnecting my code.

为了防止重新加载弹出窗口,我需要防止对Submit事件执行默认操作.我添加了一个'evt'参数来接受事件参数到提交中,并调用了preventDefault,如下所示.

In order to prevent the popup from reloading, I needed to prevent the default action on the submit event. I added an 'evt' parameter to accept the event argument to the submit, and called preventDefault as shown below.

document.getElementById('extension_form').onsubmit = function (evt)
{
    evt.preventDefault();
    ...

这使样本能够按预期工作.

This allowed the sample to work as expected.

感谢wOxxOm!