[Javascript] Google Extensions 之掃描所有開啟的 Tabs 並且拿到他的 html code ( chrome.scripting.executeScript )

2021-07-13


最近因為一些需求,我自己想寫一個小工具檢查一下網頁,因為是登入中的很懶得寫模擬登入,所以我就想到乾脆寫 Chrome Extension ,  今天的案例就是,我寫一個簡單的擴充,他可以在我  reload 隨意一個網頁,之後他會掃描我現在開啟的所有 tab ,如果其中有一個 tab 是我指定的 網址( 範例是用 https://www.google.com/),他會把該網址的 body 背景顏色變紅後,回傳整個 body  中的 html , 或許這案例很無聊,我當然要做的事情沒這麼簡單,只是寫文章幫助自己記住把案例變得簡單點...




1.  設定 manifest.json , 這裡面注意 permissions , 需要有 "tabs" , "<all_urls>"

{ "name": "DetectSK", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "run.js" }, "permissions": [ "tabs", "activeTab", "scripting", "notifications", "declarativeContent", "<all_urls>" ], "host_permissions": [ "http://*/*", "https://*/*" ], "action": {} }


2.  run.js 的部分,我就寫在 註解中.

//當有某一個 tab load 網址 chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) { //完畢之後判斷 if (changeInfo.status == 'complete') { CheckAllTabs('https://www.google.com/'); } }); //將掃描的 tab 呼叫此 function function RunTargetTabScript(){ //將背景變紅 document.body.style.backgroundColor = 'red'; //回傳 body 的 html code. return document.body.outerHTML; } function CheckAllTabs(targeturl){ chrome.tabs.query({},function(tabs){ console.log("All Open Tabs:"); tabs.forEach(function(tab){ console.log(tab.id+"-"+tab.url); //判斷是自己要處理的網址 if(tab.url.indexOf(targeturl)>-1){ //在哪個目標 tab 呼叫 ChecTabData chrome.scripting.executeScript({target: {tabId: tab.id},function: RunTargetTabScript}, (returnData) => { console.log("RETURN DATA:"); //收到 ChecTabData 回傳的資料後&#65292;印在 console 中 console.log(JSON.stringify(returnData)); }); } }); }); }
Result:





其實只是為了怕自己忘記做的筆記..


reference:

https://stackoverflow.com/questions/66788838/chrome-scripting-executescript-unexpected-property-arguments

https://stackoverflow.com/questions/16185044/get-the-urls-of-all-the-tabs-in-all-windows-using-chrome-extension


當麻許的碎念筆記 2014 | Donma Hsu Design.