2016-07-25 154 views
0

我对铬扩展开发完全陌生。 我试图改变DOM(追加数据到活动网页)当点击一个按钮在扩展弹出。这怎么可能。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> 

,当我在#键点击,我想执行的main.js文件中的一些jQuery的代码会将一些数据附加到活动网页。

谢谢。

+2

的可能的复制[Chrome扩展 - 消息从弹出传递到内容脚本](http://stackoverflow.com/问题/ 6108906/chrome-extension-message-passing-from-popup-to-content-script) –

+0

@HaibaraAi如果我的问题被这样的重复封闭,我不知道该怎么做。这只是解决方案的一小部分。 – Xan

+0

感谢您提供的链接。它有助于获得一个想法,但现在我正在寻找在popup.html中加入一个按钮,并添加一个将更改活动页面的DOM的侦听器。我正在寻找这样的东西,[链接](http://stackoverflow.com/questions/11996053/detect-a-button-click-in-the-browser-action-form-of-a-google-chrome-扩展名) –

回答

1
  1. 使用Programmatic injection。您可以在popup.js中注册事件监听器,并调用chrome.tabs.executeScript将一些js代码/文件注入当前活动选项卡。这需要主机权限。

    popup.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' }); 
        }); 
    }); 
    
  2. 使用Message Passing。您可以在popup.js中调用chrome.tabs.sendMessage,并通过content.js中的chrome.runtime.onMessage收听。

    popup.js

    // WAY 2 (Replace WAY1 with following line) 
    chrome.tabs.sendMessage(activeTabs[0].id, { action: 'executeCode' }); 
    

    content.js

    chrome.runtime.onMessage.addListener(function(request) { 
        if(request.action === 'executeCode') { 
         // YOUR CODE HERE 
        } 
    }); 
    
  3. 使用Storage。您可以在popup.js中致电chrome.storage.local.set,并通过chrome.storage.onChanged收听content.js中的存储更改。

    popup.js

    // WAY 3 (Replace WAY1 with following line) 
    chrome.storage.local.set({ action: 'executeCode' }); 
    

    content.js

    chrome.storage.onChanged.addListener(function(changes) { 
        var action = changes['action']; 
        if(action.newValue === 'executeCode') { 
         // YOUR CODE HERE 
        } 
    }); 
    
+0

谢谢Haibara。我查了一些文件。但我没有得到一个适当的想法,但这有助于 –