2016-03-21 8 views
2

私はcontent scriptsを使用しています。ウェブページにボタンを挿入したいと思います。Chrome拡張機能を使用してウェブページにボタンを挿入する方法

これは私のmanifest.json次のとおりです。

{ 
    "manifest_version": 2, 
    "name": "my extension", 
    "browser_action": { 
    "default_icon": "icon.png", 
    "default_popup": "popup.html" 
    }, 
    "permissions": [ 
    "activeTab" 
    ], 
    "content_scripts": [ 
     { 
     "matches": ["http://127.0.0.1:8000/*"], 
     "js": ["script.js"], 
     "run_at": "document_end" 
     } 
    ] 
} 

これはpopup.html次のとおりです。

<html> 
    <body> 
    <input type="button" id="button" style="display:none;"> 
    </body> 
</html> 

そしてscript.js

document.body.style.backgroundColor = "yellow"; 
var button = document.getElementById("button"); 
button.style.visibility = "visible"; 

http://127.0.0.1:8000に行くとき、私は黄色の背景の変更を参照してください、しかし、ボタンが見つからないローカルサーバーが提供するWebページの一部ではないためです。これは、このエラーを示しています

Uncaught TypeError: Cannot read property 'style' of null 

は、私は(私はその内容を知っていないと仮定)http://127.0.0.1:8000のコンテンツの上部にあるボタンを注入するために何をすべき? DOMが完了した後

答えて

3

を見つけて挿入することができるようになります。この方法は、あなたがする必要はありませんpopup.htmlでそれを宣言(べきではありません)

manifest.jsonを

{ 
    "manifest_version": 2, 
    "name": "my extension", 
    "content_scripts": [ 
     { 
     "matches": ["http://127.0.0.1:5000/*"], 
     "js": ["script.js"]   
     } 
    ] 
} 

script.js

document.body.style.backgroundColor = "yellow"; 
var button = document.createElement("button"); 
document.body.appendChild(button); 
1

あなたはdocument_endであなたのcontent_scripts財産で"run_at": "document_end"

を追加する必要があり、スクリプトファイルは、注入されます。 documentはそれをあなたコンテンツのスクリプトでそれを作成し、ボタンを挿入するには、あなたの失われたボタン:)

"content_scripts": [ 
     { 
     "matches": ["http://127.0.0.1:5000/*"], 
     "js": ["script.js"], 
     "run_at": "document_end" 
     } 
    ] 
関連する問題