Chrome扩展程序浏览文件(Chrome v33)

时间:2014-02-23 09:31:01

标签: javascript html google-chrome google-chrome-extension

我浏览过使用Chrome扩展程序的文件,但突然间它停止工作(我猜是因为Chrome升级(到v33?))

我环顾四周,所有答案似乎都过时了......

这是我的文件(我从中得到了它:Upload File as a Form Data through chrome extension

的manifest.json:

{
"background": {
    "persistent": false,
    "scripts": ["background.js"]
},

"name": "yoyo",
"manifest_version": 2,
"version": "1.0.0", 
"browser_action": {
    "default_title": "Test Extension",
    "default_popup": "popup.html"
},

"permissions": [
    "https://www.example.com/uploads"
]
}

popup.html:

<html>
<head>
    <script type="text/javascript" src="popup.js"></script>
</head>
<body>
<input type="button" id="button" value="Browse and Upload" />
</body>
</html>

popup.js:

document.addEventListener('DOMContentLoaded', function () {
    document.getElementsByTagName('input')[0].addEventListener('click', function () {
        chrome.runtime.sendMessage({ action: 'browseAndUpload' }, function(response){});
        window.close();
    });
});

background.js:

var uploadURL = 'https://www.example.com/uploads';

/* Creates an `input[type="file]` */
var fileChooser = document.createElement('input');
fileChooser.type = 'file';
fileChooser.addEventListener('change', function () {
    var file = fileChooser.files[0];
    var formData = new FormData();
    formData.append(file.name, file);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', uploadURL, true);
    xhr.addEventListener('readystatechange', function (evt) {
        console.log('ReadyState: ' + xhr.readyState,
                    'Status: ' + xhr.status);
    });

    xhr.send(formData);
    form.reset();   // <-- Resets the input so we do get a `change` event,
                    //     even if the user chooses the same file
});

/* Wrap it in a form for resetting */
var form = document.createElement('form');
form.appendChild(fileChooser);

/* Listen for messages from popup */
chrome.runtime.onMessage.addListener(function (msg) {
    if (msg.action === 'browseAndUpload') {
        fileChooser.click();
    }
});

0 个答案:

没有答案