Можно ли добавить .XML-файл в расширение Chrome для хранения / извлечения данных? - PullRequest
0 голосов
/ 20 января 2019

Я создал расширение Chrome для своего Office, и в некоторые моменты мне нужно хранить / извлекать основные данные, и я подумал о том, чтобы в одной папке находился простой файл XML с файлами manifest и js .

Что-то вроде:

 <templates>
       <template>
          <title> Invoice sent</title>
          <text>

            Dear [CUSTOMER_NAME],
            We have just issued you an invoice.
            Kindly note that the total amount does not include the Pre-export 
            inspection fee.

            **Please get back to us soonest possible, so we can reserve the 
            [PRODUCT_NAME] for you and avoid having it
            sold to a different client.

            Regards
            [STAFF_NAME]
            [DEPARTMENT_NAME]

    </text>
      </template>

      <template>
          <title>........

</templates>

Тег <templates> будет иметь несколько тегов <template> , которые будут содержать различные теги <title> и <text> .

[СОДЕРЖАНИЕ В КРОНШТЕЙНАХ] должно динамически меняться, когда XML читается javascript.

  1. Как мой .js файл получает доступ к файлу XML? (любой образец code будет высоко оценен)

  2. Как добавить файл XML в файл manifest.json, чтобы он был доступен для файла content002.js?

пока manifest.json выглядит примерно так:

{
  "manifest_version": 2,

  "name": "myExtName",
  "version": "0.1.0",
  "description": "My Browser extension",

  "content_scripts": [{
    //"css": ["styles.css"],
    "js": ["content002.js","jquery.js"],
    "matches": ["https://www.companysite.com/*","file://*"],
    "run_at": "document_end"
  }]

}

Я пытался: Как читать содержимое файла xml в jQuery и отображать его в элементах html?

Но пока безуспешно, очевидно, использование:

 $.ajax({
        type: "GET" ,
        url: "xmlFile.xml" ,
        dataType: "xml" ,

возвращает ошибку, указывающую, что $.ajax ищет xmlFile на удаленном сервере , но НЕ в расширении Chrome корневая папка

1 Ответ

0 голосов
/ 25 января 2019

Это заняло некоторое время, но, наконец, это сработало.

Вот что я сделал.

manifest.json

{
  "manifest_version": 2,

  "name": "EXTENSION NAME",
  "version": "0.1.0",
  "description": "DESCRIPTION GOES HERE",

  "content_scripts": [{

    "js": ["jq3.js","JAVASCRIPT.js"],
    "matches": ["https://*/*","file://*"],
    "run_at": "document_end"

  }],

  "web_accessible_resources": 
      ["xmlFile.xml"] //This .xml file is in the same directory with the manifest    
  }

JAVASCRIPT

var xmlCont = chrome.runtime.getURL("xmlFile.xml"); //this returns the FULL_PATH of the .xml file [NOT THE XML NODES]
            console.log(xmlCont) //You can see it here

                    $.ajax({                    
                          type: "GET" , 
                          url: xmlCont,//Place that FULL_PATH here 
                          dataType: "xml" , //This too is important 

                         success: function(xml) { 

                          console.log(xml)// see the ajax results if your curious

                        //var xmlDoc = $.parseXML( xml );//NOT NEED FOR THIS

                        //console.log(xmlDoc);// if you parseXML it returns null

                        var title = $(xml).find('value').text(); //Show the text between the <title> tags
                        console.log(title);

                    }    
                        });

XML

<rss version='2.0'>
    <channel>
        <title>
I am the text between the -title- tag
       </title>
    </channel>
</rss>

Надеюсь, это кому-нибудь поможет

...