Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Last active January 6, 2020 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pamblam/ec8cb13162f148559a4d0ae463cd7f2d to your computer and use it in GitHub Desktop.
Save Pamblam/ec8cb13162f148559a4d0ae463cd7f2d to your computer and use it in GitHub Desktop.
Search source codeof a webpage, including it's linked stylesheets and scripts.
/**
* Used to find function names or any other strings in sources of a web page.
* @param {string} needle - The string to find
* @param {boolean} caseMatch - Is search case sensitive?
*/
async function shallowSourceSearch(needle, caseMatch = false) {
var matches = [], files = [];
if (!caseMatch) needle = needle.toLowerCase();
const searchFile = async path => {
try {
var source = await fetch(path).then(r => r.text());
if (!caseMatch) source = source.toLowerCase();
for (var lines = source.split("\n"), i = lines.length; i--;) {
var match = lines[i].indexOf(needle);
if (match > -1) {
matches.push({
file: path,
line: i,
position: match,
context: lines[i]
});
}
}
} catch (e) {}
};
files.push(location.href);
var links = [...document.querySelectorAll('link')].map(l => l.href).filter(l => !!l);
var scripts = [...document.querySelectorAll('script')].map(s => s.src).filter(s => !!s);
files.push(...links, ...scripts);
await Promise.all(files.map(path => searchFile(path)));
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment