从chrome:// extensions重新加载扩展后,确保将内容脚本注入当前标签页而不进行任何页面刷新

时间:2016-06-28 12:28:22

标签: google-chrome-extension

我正在尝试制作一个扩展程序,用于从Chrome浏览器中打开的当前标签中删除电子邮件ID。

chrome://extensions重新加载扩展程序后,当我转到我要测试扩展程序的选项卡时,我必须刷新页面,以便在该页面中查看所需的结果控制台尽管使用chrome.tabs.executeScript background.js 中执行内容脚本,然后将其重新投放到浏览器的当前标签中。

内容脚本 - 相关部分

var jsonData = scrape();
console.log(jsonData);   //THIS I SEE WITHOUT PAGE REFRESH

chrome.runtime.sendMessage(jsonData, function(response) {
    console.log(response);   //WITHOUT PAGE REFRESH shows undefined, AFTER PAGE REFRESH shows the desired response
});

background.js

var background = {

    injectScript: function() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.executeScript(tabs[0].id, {file: "myscript.js"});
        });
    }

};

background.injectScript();

的manifest.json

{
    "manifest_version": 2,

    "name": "emailScraper",
    "version": "1.0",

    "description": "Email Scraping Chrome Extension",
    "icons": {
        "64": "tiki_1.3.png"
    },

    "browser_action": {
        "default_icon": "tiki_1.3.png",
        "default_popup": "popup.html"
    },

    "background": {
        "scripts": ["js/app/background.js",
                    "js/lib/socket.io/socket.io.js"]
    },

    "content_scripts": [
        {
          "matches": ["http://*/*", "https://*/*", "https://mail.google.com/*", "https://google.com/*", "file://*/*"],
          "js": ["js/lib/jquery/jquery.min.js", "js/app/myscript.js"],
          "all_frames": false
        }
    ],

    "permissions": [
        "tabs",
        "http://*/*",
        "https://*/*"
    ],

    "content_security_policy": "script-src 'self' http://localhost:1441/; object-src 'self'"
}

我还想补充一点,内容脚本正在与我的扩展程序的 popup.js 进行通信。它会将收到的电子邮件ID列表发送到 popup.js popup.js 收到列表时会向内容脚本发送响应。只有在刷新当前页面后才能进行此信息交换。我想知道为什么会这样。

popup.js

var app = angular.module('emailScraper',[]);

app.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {

    //Fetch URL of current Tab open in Chrome
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function(tabs) {
        // and use that tab to fill in out title and url
        var tab = tabs[0];

        $scope.cpUrl = tab.url;
        console.log($scope.cpUrl); //I SEE ONLY THIS LINE WHEN I INSPECT POPUP
    });

    $scope.appLoaded = false;   
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        console.log("Message received: ", request); //I SEE ONLY AFTER PAGE REFRESH IN Inspect Popup BUT NOT IN popup.html view

        $scope.emailList = request;
        $scope.count = Object.keys($scope.emailList).length;
        console.log("Emails found: " + $scope.count); //I SEE ONLY AFTER PAGE REFRESH IN Inspect Popup BUT NOT IN popup.html view
        $scope.appLoaded = true;

        sendResponse({status: "Received JSON data!"});
    });

}]);

感谢您的回复。

0 个答案:

没有答案