[英]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.