Chrome-扩展名:单击 popup.html 中的按钮,打开新标签页,填写输入

Chrome-extension: Click button from popup.html, open new tab, fill input

我是开发 chrome 扩展的新手,所以请原谅我的无知。我想制作一个弹出 html 按钮,点击事件会打开一个新选项卡并在新选项卡中填写输入字段。

这是我的示例代码。

popup.html

<button onclick="test">click me</button>

popup.js

function test() {
      
            chrome.tabs.create({ 'url': "https://www.google.com" }, function (tab) {
                var new_tab_id: number = 0;
                if (tab.id != undefined) {
                    new_tab_id = tab.id;
                }
                chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
                    chrome.tabs.sendMessage(new_tab_id, { greeting: "hello" }, function (response) {
                        console.log(response.farewell);
                    });
                });
            })

        }
    }

content.js

chrome.runtime.onMessage.addListener(
    function(request:any, sender:any, sendResponse:any) {
      console.log(sender.tab ?
                  "from a content script:" + sender.tab.url :
                  "from the extension");
      if (request.greeting == "hello") {
          const inputEl:HTMLInputElement|null = document.querySelector('input[name=q]');
          if(inputEl !== null) {
              inputEl.value = 'test input'
          }
      }      
        sendResponse({farewell: "goodbye"});
    }
  );

我做错了什么吗?新标签页的控制台,弹出窗口,背景什么都没说..

不要使用像 onclick=test 这样的内联代码。
相反,将点击侦听器添加到单独的 js 文件中,more info and examples.

打开新的前台选项卡会关闭弹出窗口,这会终止其脚本,因此不会发送消息。最简单的解决方案是使用 chrome.storage,以便内容脚本直接使用它。

manifest.json:

"permissions": ["storage"]

popup.html:

<body>
  <button id="foo">click me</button>
  <script src="popup.js"></script>
</body>

popup.js:

document.querySelector('#foo').onclick = () => {
  chrome.storage.sync.set({autofill: 'foo'}, () => {
    chrome.tabs.create({url: 'https://www.google.com'});
  });
};

content.js:

chrome.storage.sync.get('autofill', data => {
  if (data.autofill) {
    const el = document.querySelector('input[name=q]');
    if (el) el.value = data.autofill;
  }
});

另一种解决方案是从弹出窗口向后台脚本发送消息,以便后者创建选项卡并向其发送消息,但至少如果您希望它可靠的话,它会更复杂。