はじめに
HTMLページデータを JavaScriptを使って取得します。
取得するデータ用のHTML
次のページにあるデータを取得します。
sample.html
<HTML>
<BODY>
<TABLE id="personList" class="persons" border="1">
<TR class="person">
<TD class="id">123</TD>
<TD class="name">Sato Taro</TD>
<TD class="email">taro@sample.com</TD>
</TR>
<TR class="person">
<TD class="id">124</TD>
<TD class="name">Suzuki Hana</TD>
<TD class="email">hana@sample.com</TD>
</TR>
</TABLE>
</BODY>
</HTML>
background script からページへ javascriptの挿入
ページの右クリックメニューから JavaScriptを実行してデータを取得するようにプログラムを作成します。background.js からでは、実行しているページの document が取得できなかったので、JavaScript をページに挿入して実行するようにします。
ポイント
- browser.tabs.executeScript で JavaScriptをページに挿入
- 起点となる element を document.getElementById で取得
- element.childNodesでも取得できましたが、\t など余分なデータが入っていたので childrenで 子element を取得
background.js
browser.contextMenus.create({
id: "getTableData",
title: "get table data",
contexts: ["all"]
})
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "getTableData") {
let executing = browser.tabs.executeScript(
tab.id, {
file: "/gettabledata.js"
});
executing.then(function(val) {
console.log("gettabledata.js executed");
})
.catch((reason) => {
console.log('gettabledata.js failed ('+reason+') here.');
});
}
});
gettabledata.js
getTableData();
function getTableData() {
const personList = document.getElementById("personList");
const persons = [];
for (let i = 0; i < personList.children.length; i++) { // tbody
console.log(personList.children);
for (let j = 0; j < personList.children[i].children.length; j++) { // person
const person = new Object();
for (let k = 0; k < personList.children[i].children[j].children.length; k++) { // td
if (personList.children[i].children[j].children[k].className
.indexOf("id") >= 0) {
person.id = personList.children[i].children[j].children[k].innerHTML;
console.log(person.id);
}
if (personList.children[i].children[j].children[k].className
.indexOf("name") >= 0) {
person.name = personList.children[i].children[j].children[k].innerHTML;
console.log(person.name);
}
if (personList.children[i].children[j].children[k].className
.indexOf("email") >= 0) {
person.email = personList.children[i].children[j].children[k].innerHTML;
console.log(person.email);
}
}
persons.push(person);
}
}
console.log(persons);
}
まとめ
右クリックメニューで get table data を選択すると
参考
tabs.executeScript() - Mozilla | MDN
document - Web API インターフェイス | MDN
Promise - JavaScript | MDN