Open (Import) file in a chrome extension

前端 未结 1 1506
执笔经年
执笔经年 2020-12-31 05:44

I\'m trying to develop import feature for my chrome extension, but this task seems more difficult then expected.

Actually my idea is to use an



        
相关标签:
1条回答
  • 2020-12-31 06:18

    Finally I decided for the third option, which was in my opinion, and for my purposes (read content from a file and update a URL) the easiest and fastest to implement.

    Here what I did:

    In my popup.js, when the user presses the import button, I call chrome.tabs.executeScript and read a file with the code to be injected into the current tab page:

    else if(e.target.id=="import") {
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.executeScript(tabs[0].id, {file: "src/content_script.js"});
      });
    }
    

    Then I moved all the import logic in the content_script.js file, where I:

    1. Create a new input file element using document.createElement.
    2. Append this element as child of html <body>.
    3. Trigger click event from the element (it is important to remind that the .click event in chrome cannot be triggered on object that are not part of any DOM object).
    4. Handle change event for the input file.

    Here is the code:

    var fileChooser = document.createElement("input");
    fileChooser.type = 'file';
    
    fileChooser.addEventListener('change', function (evt) {
      var f = evt.target.files[0];
      if(f) {
        var reader = new FileReader();
        reader.onload = function(e) {
          var contents = e.target.result;
          /* Handle your document contents here */
          document.location.href = url_array; // My extension's logic
        }
        reader.readAsText(f);
      }
    });
    
    document.body.appendChild(fileChooser);
    fileChooser.click();
    

    It seems that in a content script I cannot access the chrome.tabs object, so in my case I just decided to use the usual document.location.href to change the URL.

    0 讨论(0)
提交回复
热议问题