Google Chrome扩展程序中的脚本加载顺序

时间:2016-11-16 05:58:34

标签: google-chrome-extension manifest.json

我是Chrome扩展编码的新手,目前我正在尝试将扩展程序构建为业余爱好

这是我的manifest.json

    {
        "manifest_version": 2,
        "name": "LOL",
        "version": "0.1",
        "background": {
            "persistent": false,
            "scripts": ["background.js", "back.js"]
        },
        "browser_action": {
            "default_icon": "icon.png",
            "default_popup": "popup.html"
        },
        "permissions": [
            "downloads", "downloads.open", "downloads.shelf", "activeTab", "background"
        ]
    }

我在 popup.html 中有两个单选按钮。点击后,我正在执行 background.js back.js

但是,即使我选择了第二个单选按钮, background.js 也正在执行。

我观察到的奇怪行为是:如果我将 manifest.json 中的脚本顺序换成 back.js background.js ..无论我选择哪个单选按钮,只有 back.js 正在执行。

我不确定我的脚本有什么问题。请说明问题所在。

这是我的popup.js

    function hello() {
        chrome.tabs.executeScript({
            file: 'background.js'
        });}

        function hello2() {
            chrome.tabs.executeScript({
                file: 'back.js'
            });
        }


    var radio1 = document.getElementById('option1').value;
    if (radio1 == "folder1") {
        document.getElementById('option1').addEventListener('click', hello);
    }
    if (radio1 == "folder2") {
        document.getElementById('option2').addEventListener('click', hello2);
    }

这是background.js

function alertlol() {

chrome.downloads.onDeterminingFilename.addListener(function(item, suggest) {
suggest({filename: "mysubdirectory/" + item.filename});
});

}
chrome.browserAction.onClicked.addListener(alertlol);
alertlol();

这是back.js

function alertlol1() {

chrome.downloads.onDeterminingFilename.addListener(function(item, suggest) {
suggest({filename: "mydir/" + item.filename});
});

}
chrome.browserAction.onClicked.addListener(alertlol1);
alertlol1();

这是popup.html

<!DOCTYPE html>
<html>
  <body style="width: 300px">
    Select download folder
    </br><input type="radio"  name="option1" onclick="background.js" value="folder1">Download folder one </input>
    <script type="text/javascript" src="popup.js"></script></br>
    <input type="radio"  name="option1" onclick="back.js" value="folder2">Download folder two </input>
    <script type="text/javascript" src="popup.js"></script>
  </body>
</html>

这是代码库

https://github.com/beardlessgenius/DLM

1 个答案:

答案 0 :(得分:0)

我可以建议的一件事是, a)在HTML的开头,body标记的开头或结尾仅使用<script type="text/javascript" src="popup.js"></script>。 b)在popup.js中,使用onclick()事件,而不是检查其值。这是因为它只检查一次值并完成处理。如果您以后单击或两次单击同一按钮怎么办?

在html中添加“ onclick”事件后,如果问题仍然存在,请ping我。这只会给您一个开始,请从这里继续。