我正在開發Google Chrome瀏覽器的擴展程序。 我無法弄清楚如何從「popup.html」頁面訪問當前標籤DOM對象。 有什麼建議嗎?從「popup.html」訪問當前選項卡DOM對象?
29
A
回答
24
默認情況下,在popup.js/popup.html中,「文檔」對象僅引用擴展的彈出窗口的文檔。要獲取特定選項卡的DOM(例如當前活動選項卡),您需要使用content scripts communications。例如,我們需要通過popup從extension的請求發送到您的內容腳本,所以在popup.html你做這樣的事:
chrome.tabs.getSelected(null, function(tab) {
// Send a request to the content script.
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
console.log(response.dom);
});
});
現在在內容腳本,我們需要從listen for those events未來延伸,所以在一些文件中,我們命名爲dom.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.action == "getDOM")
sendResponse({dom: "The dom that you want to get"});
else
sendResponse({}); // Send nothing..
});
現在還記得設置你的manifest包含內容腳本和標籤許可。
3
這個答案似乎不適用於最新的API。這是一個工作示例。
popup.js:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tab = tabs[0];
console.log(tab.url, tab.title);
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(msg) {
msg = msg || {};
console.log('onResponse', msg.farewell);
});
});
});
getDescription.js:manifest.json中的
window.onload = function() {
chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
console.log('onMessage', msg);
if (msg.greeting == "hello") {
sendResponse({farewell: "goodbye"});
} else{
sendResponse({});
}
});
};
相關部分:
{
"permissions": [
"tabs"
],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["getDescription.js"]
}
]
}
1
這是最新的補丁:
popup.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
(注:以上的console.log(response.farewell)是popup.html,不是你的當前選項卡)
contentscript.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
相關問題
- 1. 從Chrome擴展程序訪問當前選項卡DOM對象
- 2. 訪問當前對象從它自己
- 3. 從擴展和更新iframe動態注入Iframe訪問當前選項卡的DOM DOM
- 4. 如何從另一個選項卡訪問對象c#
- 5. WPF選項卡控件訪問先前的選項卡數據
- 6. 從ng選項訪問對象
- 7. 從當前選項卡的標籤中刪除選項卡
- 8. 有沒有辦法從Mobile項目訪問DOM對象
- 9. 當前對象的訪問類
- 10. 從另一頁訪問div選項卡
- 11. LWUIT:選項卡 - 如何標記當前選定的選項卡
- 12. jquery選項卡 - 在當前選項卡中加載url?
- 13. jQuery UI選項卡:獲取當前選項卡索引
- 14. Jquery選項卡在選項卡中加載當前網址
- 15. jQuery選項卡 - 當前選項卡中的參考標籤?
- 16. jQuery選項卡 - 使當前選項卡突出顯示從單獨的導航
- 17. 如何從.net訪問高級安全選項選項卡?
- 18. 訪問當前對象是其中一部分的對象
- 19. 如何從當前html中訪問其他html的dom元素
- 20. 選項卡控件訪問每個選項卡成員Winform
- 21. 可訪問的jquery選項卡 - 直接鏈接到選項卡
- 22. 訪問DOM對象模型JavascriptCore
- 23. 需要得到選定的文本從當前選項卡
- 24. 嚮導bootstrap返回當前選項卡
- 25. 抓取當前選項卡名稱
- 26. 量角器關閉當前選項卡
- 27. 添加類當前菜單選項卡
- 28. 關閉當前打開的選項卡
- 29. 如何激活當前選項卡
- 30. 自舉ajax選項卡刷新當前
我的意思是DOM是文檔對象模型...謝謝 – 2009-12-27 12:54:05
是的,我在示例中展示的是在Chrome擴展中完成的同步消息。我返回了一個字符串「你想得到的dom」,但實際上,你可以返回任何你想要的DOM。如果你想獲得所有的東西,你可以做「sendResponse({dom:document.getElementsByTagName(」body「)[0]});」 – 2009-12-28 03:08:05
做了上面的例子嗎? AFAIK發送響應會將dom序列化爲json,這可能會導致由於dom對象的圓形結構而導致的錯誤。 – 2011-06-28 14:44:39