6

アイコンをクリックするとポップアップが表示される chrome 拡張機能があり、そのポップアップにデータを入力するためのテキスト ボックスがあるとしたら、テキスト ボックス内のテキストを取得する JavaScript はどのように見えるでしょうか?

更新: テキスト ボックスから値を取得する方法は知っていますが、私の質問は、特に popup.html ファイルの要素にアクセスするにはどうすればよいですか? document.getElementById ect ect にアクセスしようとしましたが、カスタム ポップアップではなく、実際のページ コンテンツ内の要素を取得します。

4

2 に答える 2

11

次の方法で、ボタンのクリックイベントなどのイベントのイベントリスナーをバインドすることにより、ポップアップページのテキストボックスから値を取得できます。

manifest.json ファイルが次のようになっているとします。

{
  "manifest_version": 2,

  "name": "Wonderful extension",
  "description": "Wonderful extension - gets value from textbox",
  "version": "1.0",

  "browser_action": {
   "default_icon": "images/icon.png",
   "default_popup": "popup.html"
  } 
}

popup.html は次のようになります。

<!DOCTYPE html>
<html>
  <head>
    <title>Wonderful Extension</title>
    <script src="popup.js"></script>     
  </head>
  <body>   

    <div style="padding: 20px 20px 20px 20px;">           
        <h3>Hello,</h3>
        <p>Please enter your name : </p>         
        <input id="name_textbox" />                   
         <button id="ok_btn" type="button">OK</button>
    </div>      

  </body>
</html>

次に、次の方法でテキストボックスから値を取得するために、ドキュメント内のイベントをバインドできます。

ファイル popup.js :

document.addEventListener('DOMContentLoaded', documentEvents  , false);

function myAction(input) { 
    console.log("input value is : " + input.value);
    alert("The entered data is : " + input.value);
    // do processing with data
    // you need to right click the extension icon and choose "inspect popup"
    // to view the messages appearing on the console.
}

function documentEvents() {    
  document.getElementById('ok_btn').addEventListener('click', 
    function() { myAction(document.getElementById('name_textbox'));
  });

  // you can add listeners for other objects ( like other buttons ) here 
}

ポップアップ ページの他の要素にアクセスするには、同様の方法を使用できます。

于 2016-03-26T09:04:38.910 に答える