通过Chrome扩展程序将文件上传为表单数据

Arv*_*ala 28 javascript google-chrome google-chrome-extension

我通过chrome扩展程序上传文件作为表单数据,我的代码如下所示.这里的问题是文件浏览窗口打开一秒钟然后消失.
该问题仅出现在Mac OS中.

manifest.json的:

"background": {
  "scripts": ["jszip.js", "background.js"]
},
Run Code Online (Sandbox Code Playgroud)

background.js:

chrome.runtime.onMessage.addListener(function (msg) {
  if (msg.action === 'browse')
  {
    var myForm=document.createElement("FORM");
    var myFile=document.createElement("INPUT");
    myFile.type="file";
    myFile.id="selectFile";
    //myFile.onclick="openDialog()";
    myForm.appendChild(myFile);
    var myButton=document.createElement("INPUT");
    myButton.name="submit";
    myButton.type="submit";
    myButton.value="Submit";
    myForm.appendChild(myButton);
    document.body.appendChild(myForm);
  }
});
Run Code Online (Sandbox Code Playgroud)

popup.js:

window.onload = function () {
  chrome.runtime.sendMessage({
    action: 'browse'
  });
}
Run Code Online (Sandbox Code Playgroud)

gka*_*pak 16

一个小小的"背景故事":

您希望让用户从弹出窗口中选择并上传文件.但是在OSX中,只要文件选择器对话框打开,弹出窗口就会失去焦点并关闭,从而导致其JS上下文被破坏.因此,对话框立即打开和关闭.

这是MAC上已知的一段时间的错误.


解决方案:

您可以将对话框打开逻辑移动到后台页面,该页面不受失去焦点的影响.在弹出窗口中,您可以向后台页面发送消息,请求启动浏览和上载过程(请参阅下面的示例代码).

的manifest.json

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

    "browser_action": {
        "default_title": "Test Extension",
//        "default_icon": {
//            "19": "img/icon19.png",
//            "38": "img/icon38.png"
//        },
        "default_popup": "popup.html"
    },

    "permissions": [
        "https://www.example.com/uploads"
        // The above permission is needed for cross-domain XHR
    ]
}
Run Code Online (Sandbox Code Playgroud)

popup.html

    ...
    <script src="popup.js"></script>
</head>
<body>
    <input type="button" id="button" value="Browse and Upload" />
    ...
Run Code Online (Sandbox Code Playgroud)

popup.js

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('button').addEventListener('click', function () {
        chrome.runtime.sendMessage({ action: 'browseAndUpload' });
        window.close();
    });
});
Run Code Online (Sandbox Code Playgroud)

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();
    }
});
Run Code Online (Sandbox Code Playgroud)

抬头:
作为安全预防措施,fileChooser.click() 只有在用户互动的结果下,Chrome才会执行.
在上面的示例中,用户单击弹出窗口中的按钮,该按钮将消息发送到后台页面,该页面调用fileChooser.click();.如果您尝试以编程方式调用它将无法正常工作.(例如,在文档加载时调用它不会有任何影响.)

  • 嗨!我尝试了这个解决方案,在Windows 7(chrome ver.37)下,并没有触发.click事件.(与@ExpertSystem评论相同).我还尝试将文件加载逻辑直接放在弹出窗口(window.html/js)中,但是一旦单击按钮,弹出窗口就会关闭.如果我打开开发人员工具窗口(右键单击插件图标 - > Inspect弹出窗口),它只会保持正常(并正确执行文件加载).任何想法/解决方案? (3认同)

Ray*_*ear 7

ExpertSystem的解决方案对我不起作用,因为它不会让我调用后台脚本中的元素点击,但我想出了一个使用他的大部分代码的解决方法.如果您没有稍微污染当前选项卡的问题,请将他的background.js代码放在内容脚本中,并使用正确的消息传递包装器.大多数功劳归功于ExpertSystem,我只是改变了一切.

背景:

我需要解决的问题是我想通过弹出窗口上传JSON文件并将其解析到我的扩展中.我想出来的解决方法就是要求所有三件作品都有复杂的舞蹈; 弹出窗口,背景和内容脚本.

popup.js

// handler for import button
// sends a message to the content script to create the file input element and click it
$('#import-button').click(function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {message: "chooseFile"}, function(response) {
            console.log(response.response);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

content.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.message == "chooseFile") {
        /* Creates an `input[type="file]` */
        var fileChooser = document.createElement('input');
        fileChooser.type = 'file';

        fileChooser.addEventListener('change', function () {
            console.log("file change");
            var file = fileChooser.files[0];

            var reader = new FileReader();
            reader.onload = function(){
                var data = reader.result;
                fields = $.parseJSON(data);
                // now send the message to the background
                chrome.runtime.sendMessage({message: "import", fields: fields}, function(response) {
                    console.log(response.response);
                });
            };
            reader.readAsText(file);
            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);

        fileChooser.click();
        sendResponse({response: "fileChooser clicked"});
    }

});
Run Code Online (Sandbox Code Playgroud)

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.message == "import") {
        fields = request.fields; // use the data
        sendResponse({response: "imported"});
    }
});
Run Code Online (Sandbox Code Playgroud)

其他可能或可能不工作的原因是因为文件输入元素是在当前选项卡的范围内创建的,该范围在整个过程中持续存在.