How to read and display file in a chrome extension

六月ゝ 毕业季﹏ 提交于 2021-02-04 14:56:10

问题


I want to read and display the contents of file in a chrome extension (The file is already inside the extension directory).How do it?Whether I can use HTML5 to read it?

  var elema3 = document.body.getElementsByClassName("slicefooter");
  elema3[0].innerHTML='Shanmuga Subramanian';

  var a1=chrome.extension.getURL('script1.txt');
  var reader = new FileReader();
  reader.readAsText(a1);

回答1:


Use XMLHttpRequest.

Example:

var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('script1.txt'), true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200)
    {
        //... The content has been read in xhr.responseText
    }
};
xhr.send();



回答2:


A better option would be to store the contents of your text in your HTML itself using something like

<script id="textFile" type="text/x-template">...</script>

and then reference the contents of the template via document.getElementById('textFile').

Let me know if you need more information.




回答3:


Although this is a very late answer, it might help those struggling with this today:

For this to work properly you have to include the following in your manifest.json and replace <path> with the relative path to the file from the extension's root folder e.g. images/my_dog.png:

"web_accessible_resources": [
    "<path>"
]

Read more here: https://dev.to/aussieguy/reading-files-in-a-chrome-extension--2c03



来源:https://stackoverflow.com/questions/13832251/how-to-read-and-display-file-in-a-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!