[英]How would I go about this? (Chrome extension)
我是創建擴展的新手,我正努力使它們變得更舒適。 基本上,我正在嘗試創建一個執行以下操作的簡單擴展:
我不確定如何使用擴展名單擊新窗口中的按鈕。 我該如何處理? 這就是我現在所擁有的:
popup.html
<html>
<body>
<input type="button" id="the_button" value="My button"></input>
</body>
<script src="popup.js"></script>
</html>
popup.js
document.getElementById("the_button").addEventListener("click", function() {
var win = window.open("http://www.roblox.com", "roblox", 400, 400)
//Now what can I do to externally click buttons?
})
manifest.json
{
"manifest_version": 2,
"name": "Test",
"description": "Test Extension",
"version": "1.0",
"icons": {
"48": "icon.png"
},
"permissions": [
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*", "http://*/*"],
"js": ["jquery.js", "popup.js"]
}],
"browser_action": {
"default_title": "This is a test",
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
首先,使用</input>
結束標記犯了一個錯誤: <input>
標記不需要關閉! 因此,將您的popup.html
更改為:
<html>
<body>
<input type="button" id="the_button" value="My button">
</body>
<script src="popup.js"></script>
</html>
現在,進入真正的問題:
您需要創建一個新選項卡,然后將內容腳本插入頁面。 這是一個快速的解決方案:
將tabs
權限添加到manifest.json
:
... "permissions": [ "*://*/*", // this will match both http and https :) "tabs" ], ...
從清單中刪除popup.js
內容腳本 ,這是沒有用的! 不用了
... "content_scripts": [{ // remove! "matches": ["http://*/*", "http://*/*"], // remove! "js": ["jquery.js", "popup.js"] // remove! }], // remove! ...
警告 :當我說刪除時 ,是指從您的manifest.json
徹底刪除該行,不要使用注釋( //
),也不要在代碼上復制並粘貼我的代碼,只需刪除那四行。
現在,在您的popup.js
您可以在打開標簽頁時在頁面內注入內容腳本,如下所示:
document.getElementById("the_button").addEventListener("click", function() { chrome.tabs.open({url:"http://www.roblox.com", active:"true"}, function(tab) { chrome.tabs.executeScript(tab.id, {file:"click_the_button.js", run_at: "document_end"}); // here is where you inject the content script ^^ } });
這將創建一個新選項卡,並將腳本click_the_button.js
注入其中,您將使用該腳本單擊頁面內的按鈕(加載時),其代碼為:
var thing = $("a#roblox-confirm-btn"); thing.click();
注意:如果要在click_the_button.js
腳本中使用jQuery,也可以在其選項卡中插入jQuery:
document.getElementById("the_button").addEventListener("click", function() {
chrome.tabs.open({url:"http://www.roblox.com", active:"true"}, function(tab) {
chrome.tabs.executeScript(tab.id, {file:"jQuery.js", run_at: "document_start"});
chrome.tabs.executeScript(tab.id, {file:"click_the_button.js", run_at: "document_end"});
}
});
您可能會發現有用的資源:
您需要標簽權限。 我之前也遇到過同樣的問題。 答案在這里:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.