2016-03-21 584 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我看到背景變爲黃色,但它沒有找到按鈕因爲它不是我的本地服務器提供的網頁的一部分。它顯示了這個錯誤:

Uncaught TypeError: Cannot read property 'style' of null 

我應該怎麼做http://127.0.0.1:8000注入的內容頂部的按鈕(假設我不知道它的內容)?

回答

3

要插入一個按鈕,只需在您的內容腳本創建並插入它,你需要不(應該)宣佈它

的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

你應該在你content_scripts財產

添加"run_at": "document_end"document_end,在DOM完成後,該腳本文件將被注入。在popup.html這樣,document就能找到你丟失的按鈕:)

"content_scripts": [ 
     { 
     "matches": ["http://127.0.0.1:5000/*"], 
     "js": ["script.js"], 
     "run_at": "document_end" 
     } 
    ]