(dom, parseOptions)
| 1192 | * 从一个dom节点去获取json内容,这里面有很多的判断 |
| 1193 | */ |
| 1194 | let _getJsonContentFromDOM = function (dom, parseOptions) { |
| 1195 | if (!document.body) { |
| 1196 | return false; |
| 1197 | } |
| 1198 | |
| 1199 | let candidates = []; |
| 1200 | let seen = new Set(); |
| 1201 | let addCandidate = text => { |
| 1202 | text = (text || '').trim(); |
| 1203 | if (text && !seen.has(text)) { |
| 1204 | seen.add(text); |
| 1205 | candidates.push(text); |
| 1206 | } |
| 1207 | }; |
| 1208 | let isVisibleElement = elm => elm && elm.nodeType === Node.ELEMENT_NODE && (elm.offsetHeight + elm.offsetWidth !== 0); |
| 1209 | |
| 1210 | addCandidate(dom && dom.textContent); |
| 1211 | |
| 1212 | let directText = ''; |
| 1213 | Array.from(document.body.childNodes).forEach(elm => { |
| 1214 | if (elm.nodeType === Node.TEXT_NODE) { |
| 1215 | directText += elm.textContent || ''; |
| 1216 | } |
| 1217 | }); |
| 1218 | addCandidate(directText); |
| 1219 | |
| 1220 | Array.from(document.querySelectorAll('body>pre')).forEach(elm => addCandidate(elm.textContent)); |
| 1221 | |
| 1222 | if (document.contentType === 'application/json') { |
| 1223 | addCandidate(document.body.innerText); |
| 1224 | Array.from(document.body.children).forEach(elm => { |
| 1225 | const tagName = elm.tagName.toLowerCase(); |
| 1226 | if (!['script', 'style', 'link'].includes(tagName) && isVisibleElement(elm)) { |
| 1227 | addCandidate(elm.innerText || elm.textContent); |
| 1228 | } |
| 1229 | }); |
| 1230 | } |
| 1231 | |
| 1232 | addCandidate(document.body.textContent); |
| 1233 | |
| 1234 | for (let i = 0; i < candidates.length; i++) { |
| 1235 | if (_parseJsonLike(candidates[i], parseOptions)) { |
| 1236 | return candidates[i]; |
| 1237 | } |
| 1238 | } |
| 1239 | |
| 1240 | return false; |
| 1241 | }; |
| 1242 | |
| 1243 | /** |
| 1244 | * 从页面提取JSON文本 |
no test coverage detected