[英]Chrome extension to change DOM with a button in extension popup
我對 chrome 擴展開發完全陌生。 單擊擴展彈出窗口中的按鈕時,我試圖更改 DOM(將數據附加到活動網頁)。 這怎么可能。
清單文件
{
"manifest_version": 2,
"name": "test 2",
"description": "test ext 2",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["jquery.min.js", "main.js"]
}
],
"permissions": [
"activeTab"
]
}
假設 popup.html 文件是
<!doctype html>
<html>
<head>
<title>test extension 2</title>
<script src="popup.js"></script>
</head>
<body>
<a id="button">button</a>
</body>
</html>
當我點擊#button 時,我想在 main.js 文件中執行一些 jquery 代碼,它將一些數據附加到活動網頁。
謝謝。
使用程序化注入。 您可以在 popup.js 中注冊事件偵聽器並調用chrome.tabs.executeScript
將一些 js 代碼/文件注入當前活動選項卡。 這需要主機權限。
彈出窗口.js
document.getElementById('button').addEventListener('click', function() { chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) { // WAY 1 chrome.tabs.executeScript(activeTabs[0].id, { code: 'YOUR CODE HERE' }); }); });
使用消息傳遞。 你可以稱之為chrome.tabs.sendMessage
在popup.js,並通過聽那個chrome.runtime.onMessage
在content.js。
彈出窗口.js
// WAY 2 (Replace WAY1 with following line) chrome.tabs.sendMessage(activeTabs[0].id, { action: 'executeCode' });
內容.js
chrome.runtime.onMessage.addListener(function(request) { if(request.action === 'executeCode') { // YOUR CODE HERE } });
使用存儲。 您可以在 popup.js 中調用chrome.storage.local.set
並通過chrome.storage.onChanged
監聽 content.js 中的存儲變化。
彈出窗口.js
// WAY 3 (Replace WAY1 with following line) chrome.storage.local.set({ action: 'executeCode' });
內容.js
chrome.storage.onChanged.addListener(function(changes) { var action = changes['action']; if(action.newValue === 'executeCode') { // YOUR CODE HERE } });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.