簡體   English   中英

使用來自popup.html的數據填寫表單

[英]Fill forms with a data from popup.html

我一直在嘗試創建一個擴展程序,該擴展程序用彈出式窗口中的數據填充表單,對於“背景”和“內容”文件的使用我有點困惑,我認為我不需要一個。 這是我的代碼:

表現:

 {
  "name": "Browser action for Form",
  "description": "Fill a form with data from the popup",
  "version": "1.0",
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "browser_action": {
      "default_title": "Form Test",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "content_scripts": [
    {
       "matches": ["https://the-site-with-a-form.com/*"],
       "js": ["jquery-3.1.1.min.js", "content.js"]
    }
  ],
  "manifest_version": 2
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Form</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <form>
        <textarea id="txtArea"></textarea>
        <input type="button" id="btn1" value="Run">
    </form>
  </body>
</html>

popup.js

function click(){
var text = document.getElementById("txtArea")
chrome.tabs.sendMessage(
      tabs[0].id,
    {from: 'popup', subject: 'DOMInfo',data1: text});

}

content.js

chrome.runtime.onMessage.addListener(function (msg, sender, response) {
if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
//Fill the form with the data of the popup
document.getElementById("The textbox from the form").value = msg.data1;
}
});

代碼有什么問題? 謝謝!

請學習調試擴展彈出窗口 如果這樣做,您將看到一條提示性的錯誤消息。

考慮到這一點,彈出代碼中的tabs並非來自任何地方-因此,您的代碼在那里停止並出現錯誤。 顯然,該部分已脫離上下文(很可能是tabs.query調用)。 請注意,如果您要向當前活動的選項卡發送消息,則可以完全跳過sendMessage的第一個參數。

您defintiely 確實需要一個內容腳本,因為它是一個擴展,可以與網頁的形式進行交互的唯一部分。 推薦閱讀: 所有類型的Chrome擴展程序腳本如何工作?

這是帶有固定的“ tabs”參數的popup.js

function click(e) {

    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        var activeTab = tabs[0];
        var text = document.getElementById("txtArea").value;
        chrome.tabs.sendMessage(activeTab.id, {from: 'popup', subject: 'DOMInfo',data1: text});
       });  
   window.close();
}

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('submitBtn').addEventListener('click', click); 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM