Запускатель скрипта в активной вкладке хрома

Discussion in 'Javascript' started by ckpunmkug, 15 May 2019.

  1. ckpunmkug

    ckpunmkug Member

    Joined:
    20 Mar 2017
    Messages:
    31
    Likes Received:
    12
    Reputations:
    1
    Расширение для хрома, которое при нажатии Alt+Shift+1 исполнит скрипт из файла script.js, внутри страницы загруженной в активной вкладке.

    Кодовое имя: JSInjector

    manifest.json
    Code:
    {
        "manifest_version": 2
        ,"name": "Inject and execute script.js in active tab"
        ,"version": "0.0.0.1"
        ,"background": {
            "scripts":[
                "background.js"
            ]
        }
        ,"permissions": [
            "tabs"
            ,"http://*/"
            ,"https://*/"
        ]
        ,"commands": {
            "start": {
                "suggested_key": {
                    "default": "Alt+Shift+1"
                }
                ,"description": "Execute script.js"
    
            }
        }
    }
    
    background.js
    Code:
    function resolve(variable) {
        return variable;
    }
    function reject(reason) {
        console.error(reason);
        return false;
    }
    
    function findAllTabs() {
        return new Promise((resolve, reject) => {
            chrome.tabs.query({}, resolve);
        });
    }
    
    function executeScript(tabId, fileName) {
        return new Promise((resolve, reject) => {
            chrome.tabs.executeScript(tabId, {file: fileName}, resolve);
        });
    }
    
    async function execute() {
        var tabs = await findAllTabs();
        for (var index in tabs) {
            if (tabs[index].active)
                break;
        }
        var ret = await executeScript(tabs[index].id, "script.js");
        if (typeof(ret) != "object") {
            console.error("execution script error");
            return false;
        }
        console.log(ret[0]);
    }
    
    chrome.commands.onCommand.addListener(function(launch) {
        switch(launch) {
            case "start":
                execute();
                break;
        }
    });
    
    script.js
    Code:
    var res = null;
    console.log("Worked"); // print in tab console
    res = true; // return true to background script
    
    Код который высрет, в консоль таба, сцылы из выдачи яшки
    Code:
    A = document.getElementsByClassName("link link_theme_normal organic__url link_cropped_no i-bem");
    var text = "";
    for (var index in A) {
        if (typeof(A[index].href) == "string")
            text += A[index].href+"\n";
    }
    console.log(text);
    text = text;