63 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			63 lines
		
	
	
		
			2.0 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
| chrome.runtime.onMessage.addListener(
 | |
|     function (request, sender, sendResponse) {
 | |
|         // console.log(request);
 | |
|         if (request.from == "DataExtracter:Extract") {
 | |
|             let data = extractData(request.itemsSelector, request.fieldSelectors);
 | |
|             if (sendResponse) sendResponse(data);
 | |
|         } else if (request.from == "DataExtracter:GotoUrl") {
 | |
|             window.location.replace(request.url);
 | |
|         } else if (request.from == "DataExtracter:ReportIn") {
 | |
|             if (sendResponse) sendResponse(request.from);
 | |
|         } else if (request.from == "DataExtracter:QueryUrl") {
 | |
|             if (sendResponse) sendResponse(window.location.href);
 | |
|         }
 | |
|     }
 | |
| );
 | |
| 
 | |
| function extractData(itemsSelector, fieldSelectors) {
 | |
|     return $(itemsSelector).toArray().map(
 | |
|         item => fieldSelectors.map(
 | |
|             cls => $(item).find(cls).toArray().map(find => find.textContent.trim()).join('\n')
 | |
|         )
 | |
|     );
 | |
| }
 | |
| 
 | |
| function extract(...args) {
 | |
|     let sig = `Invalid call args.
 | |
| 
 | |
| function extract(itemsSelector:string, fieldSelectors:string[])
 | |
| function extract(itemsSelector:string, fieldSelectors:string[], url:string, from:number, to:number, interval:number)
 | |
| function extract(itemsSelector:string, fieldSelectors:string, url:string, pages:number[])`;
 | |
|     if (!testArgs(...args)) {
 | |
|         console.log(sig);
 | |
|         return;
 | |
|     }
 | |
|     if (args.length == 2) {
 | |
|         saveFileAsk(extractData(args[0], args[1]));
 | |
|         return;
 | |
|     }
 | |
|     let message = {
 | |
|         from: "DataExtracter:Extract",
 | |
|         args: args
 | |
|     }
 | |
|     chrome.runtime.sendMessage(message, r => {
 | |
|         if (r) {
 | |
|             console.log(r);
 | |
|             alert(r);
 | |
|         }
 | |
|     });
 | |
| }
 | |
| 
 | |
| function testArgs(...args) {
 | |
| 
 | |
|     if (args.length < 2) return false;
 | |
| 
 | |
|     if (args.length == 2)
 | |
|         return (args[0] && args[1] && (typeof args[0] == "string") && (args[1] instanceof Array))
 | |
| 
 | |
|     let urls = [];
 | |
|     if (args.length > 2) return (typeof args[2] == "string") && (
 | |
|         (args[3] instanceof Array) ||
 | |
|         (!isNaN(args[3]) && !isNaN(args[4]) && !isNaN(args[5]))
 | |
|     )
 | |
| } |