2016-04-20 148 views
1

我完全不知所措。我想從Chrome中的標籤中獲取html內容。從標籤頁獲取HTML內容

的manifest.json

{ 
    "manifest_version": 2, 
    "name": "Test",is a test.", 
    "version": "1.0", 
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", 
    "background": { 
     "scripts": ["main.js"], 
     "persistent": false 
    }, 
    "permissions": [ 
    "tabs", 
    "https://www.google.com" 
    ] 
} 

main.js

var timerObj = new Timer({'interval':5000}); 

chrome.runtime.onStartup.addListener(timerObj.start(mainF)); 

function mainF() { 
    chrome.tabs.query({} ,function (tabs) { 
    for (var i = 0; i < tabs.length; i++) { 
     var url = tabs[i].url; 
     if (url != null) { 
      console.log(tabs[i].url); 
      //I want to get html source here 
     } 
    } 
    }); 
}; 

function Timer(obj){ 

最後一行function Timer(obj){被截斷簡潔。 console.log(tabs[i].url);用於測試。對於每個標籤,我希望獲得html源代碼。有了這個來源,我會解析標籤和其他內容。我見過其他資源提及sendMessageonMessage,但我並沒有真正瞭解它。許多其他資源指代已棄用的sendRequestonRequest

回答

2

據我所知,有三種方法來實現這一點。

  1. chrome.tabs.executeScript。我們可以使用Programming Injection將內容腳本注入到網頁中,在回調中我們可以得到返回的值。

  2. Content ScriptMessage Passing。我們也可以用manifest.json的方式注入內容腳本,然後使用chrome.runtime.sendMessagechrome.runtime.onMessage來傳輸數據。

  3. XMLHttpRequest。是的,這也是一種方式,我們可以直接在後臺頁面進行ajax調用,以獲取網頁的源代碼,因爲我們可以輕鬆獲取網址。顯然我們需要啓動另一個http請求,與上面兩種方法相比,但這也是一種方法。

在下面的示例代碼,我只是用browserAction觸發事件,那麼你可以切換不同的方法被註釋掉其它兩種方法並保留唯一一個獲得網頁的源代碼。

的manifest.json

{ 
    "manifest_version": 2, 
    "name": "Test is a test.", 
    "version": "1.0", 
    "content_scripts": [ 
     { 
      "matches": [ 
       "<all_urls>" 
      ], 
      "js": [ 
       "content.js" 
      ] 
     } 
    ], 
    "background": { 
     "scripts": [ 
      "background.js" 
     ], 
     "persistent": false 
    }, 
    "browser_action": { 
     "default_title": "title" 
    }, 
    "permissions": [ 
     "tabs", 
     "<all_urls>" 
    ] 
} 

background.js

chrome.browserAction.onClicked.addListener(function() { 
    chrome.tabs.query({}, function (tabs) { 
     for (var i = 0; i < tabs.length; i++) { 
      var id = tabs[i].id; 
      var url = tabs[i].url; 
      //method1(id); 
      method2(id); 
      //method3(url); 
     } 
    }); 
}); 

function method1(tabId) { 
    chrome.tabs.executeScript(tabId, { "code": "document.documentElement.outerHTML;" }, function (result) { 
     console.log(result); 
    }); 
} 

function method2(id) { 
    chrome.tabs.sendMessage(id, {action: "getSource"}, function(response) { 
     console.log(response.sourceCode); 
    }); 
} 

function method3(url) { 
    var xhr = new XMLHttpRequest(); 
    xhr.onload = function() { 
     console.log(xhr.responseText); 
    }; 
    xhr.open("GET", url); 
    xhr.send(); 
} 

content.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    if(request.action === "getSource") { 
     sendResponse({sourceCode: document.documentElement.outerHTML}); 
    } 
});