2016-08-11 49 views
0

我正在構建一個Google Chrome擴展,它爲對象的「特定網站」的DOM「刮」並在JavaScript函數中處理它們。如何將一個Angular對象傳遞給Google Chrome擴展中的Javascript函數?

目前我正在使用chrome.tabs.query API在後臺頁面中執行操作。我能拉出來的數據URL與

chrome.tabs.query({ 'active': true, 'lastFocusedWindow': true }, function (tabs) { 
    var url = tabs[0].url; 
    console.log(url); 
    var s = url.split('?')[1]; 
    var installation = s.split('&')[0]; 
    full_url = 'http://domain.com/' + url; 
    window.open(full_url, '_blank'); 
}); 

但現在我想從頁面的DOM的角度對象傳遞給類似的功能:

chrome.tabs.query({ "active": true, "lastFocusedWindow": true }, function (tabs) { 
     var dom_el = this.document.querySelector('[ng-controller="chartNewController"]'); 
     var ng_el = this.angular.element(dom_el); 
     var ng_el_scope = this.ng_el.scope(); 
     var address = this.ng_el_scope.fullAddress; 
    console.log(address); 
}); 

而且我得到的以下錯誤:

Cannot read property 'querySelector' of undefined at null.callback

我不知道我會有關的最有效的方法,所以我的問題是:如何在雷加後臺HTML頁面的DOM來「湊」角物體最優化的方式ds構建一個Chrome擴展?

+1

您必須使用[內容腳本](https://developer.chrome.com/extensions/content_scripts) –

回答

2

有以下行兩個錯誤:

var dom_el = this.document.querySelector('[ng-controller="chartNewController"]'); 
  1. this指回調,沒有物業documentthis對象
  2. 事件,如果你直接使用document.querySelector...,你會仍無法獲取元素,因爲當您在背景頁面中調用此行時,document指向背景頁面文檔而不是網頁。

一個建議是使用Message Passing來獲取值,你需要一個content script並建立它和背景頁面之間的通信。

背景頁:

chrome.tabs.query({ "active": true, "lastFocusedWindow": true }, function (tabs) { 
    chrome.tabs.sendMessage(tabs[0].id, {action: 'get'}, function(response) { 
     console.log(response.address); 
    }); 
}); 

內容的腳本(您將需要獲取正確的角度對象,這就要看你的網頁上,我不能與幫助):

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){ 
    if(request.action === 'get') { 
     var dom_el = document.querySelector('[ng-controller="chartNewController"]'); 
     // Ensure retrieving the correct angular object (The previous this object), that depends on your web page environment. 
     var ng_el = angular.element(dom_el); 
     var ng_el_scope = ng_el.scope(); 
     var address = ng_el_scope.fullAddress; 
     sendResponse({ address: address }); 
    } 
}); 
-1

對於那些有類似問題的人,我發現你也可以使用

 chrome.tabs.executeScript({ 
     code: 'console.log('Hello World')' 
    }); 
將原始代碼注入網頁

我遇到鉻擴展文件找不到錯誤時遇到此解決方案。我相信有什麼代碼可以實際注入頁面的限制,但我不是100%確定確切的限制。

相關問題