Требуется помощь для преобразования встроенного сценария JS во внешний файл? - PullRequest
0 голосов
/ 27 февраля 2020

С некоторой помощью пользователя добавление у меня теперь есть рабочий скрипт, который выполняет следующее:

Код для этого:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
  var spData = null;
  function doData(json) {
      spData = json.feed.entry;
  }
  
  function drawCell(tr, val) {
      var td = $("<td/>");
      tr.append(td);
      td.append(val);
      return td;
  }
  function drawRow(table, rowData) {
	  if (rowData == null) return null;
	  if (rowData.length == 0) return null;
	  var tr = $("<tr/>");
	  table.append(tr);
	  for(var c=0; c<rowData.length; c++) {
		  drawCell(tr, rowData[c]);
	  }
	  return tr;
  }
  
  function drawTable(parent) {
	  var table = $("<table/>");
	  parent.append(table);
	  return table;
  }
  
  function readData(parent) {
      var data = spData;
      var table = drawTable(parent);
      var rowData = [];
      
      for(var r=0; r<data.length; r++) {
          var cell = data[r]["gs$cell"];
          var val = cell["$t"];
          if (cell.col == 1) {
              drawRow(table, rowData);
              rowData = [];
          }
          rowData.push(val);
      }
      drawRow(table, rowData);
  }
  $(document).ready(function(){
      readData($("#data"));
      searchTable( 'dragon', document.querySelector('table') );
  });

  function searchTable(searchStr, target)
  {
        let rows = Array.from( target.querySelectorAll('tr') );
        rows.forEach( (row,idx,col) => {
                                let firstCell = row.querySelector('td').textContent;
                                if (firstCell == searchStr)
                                {
                                      let cell2 = row.querySelectorAll('td')[1].textContent;
                                      console.log(`${searchStr} found in row ${idx}`);
                                      console.log(`col 2 of row #${idx} is: ${cell2}`);
                                }
                          }
                    );
  }


  </script>
<script src="https://spreadsheets.google.com/feeds/cells/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/1/public/values?alt=json-in-script&callback=doData"></script>
<style type="text/css" media="print">
  form {display: none;}
</style>
</head>
<body>
<div id="data"/>
</body>
</html>

Код отлично работает при запуске в качестве веб-страницы.

В этом случае я хотел бы встроить страницу в расширение Chrome, чтобы график отображался в расширении Chrome. У меня проблема в том, что скрипт запускается как встроенный скрипт, что запрещено согласно Chrome CSP. Понятно, что если я пытаюсь это сделать, консоль регистрирует следующие ошибки:

callback.html:1
Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

callback.html:4
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256'), or a nonce ('nonce-...') is required to enable inline execution.

callback.html:1
Refused to load the script 'https://spreadsheets.google.com/feeds/cells/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/1/public/values?alt=json-in-script&callback=doData' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Мне было интересно, есть ли способ вместо этого использовать альтернативу внешнего файла для извлечения Google Sheet. Я знаю, что проблема с сценарием ajax может быть решена путем включения локальной версии файла jquery.min.js в мой пакет Chrome Extension, но я не уверен, что то же самое можно сделать для другого встроенного сценария.

Любая помощь будет принята с благодарностью!

1 Ответ

0 голосов
/ 28 февраля 2020

Для этого я вызываю ваш HTML индекс файла. html, а файл, в который я переместил скрипт, называется myScript. js, который находится в том же каталоге.

index . html

<html>

<head>
  <meta http-equiv="Content-Security-Policy" content="default-src *;">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="./myScript.js"></script>
  <script src="https://spreadsheets.google.com/feeds/cells/1P9DhWOHcl14Y7-P5wCxTm-sUceckGquPoOobO75XhvM/1/public/values?alt=json-in-script&callback=doData"></script>
  <style type="text/css" media="print">
    form {
      display: none;
    }
  </style>
</head>

<body>
  <div id="data" />
</body>

</html>

myScript. js

var spData = null;

function doData(json) {
  spData = json.feed.entry;
}

function drawCell(tr, val) {
  var td = $("<td/>");
  tr.append(td);
  td.append(val);
  return td;
}

function drawRow(table, rowData) {
  if (rowData == null) return null;
  if (rowData.length == 0) return null;
  var tr = $("<tr/>");
  table.append(tr);
  for (var c = 0; c < rowData.length; c++) {
    drawCell(tr, rowData[c]);
  }
  return tr;
}

function drawTable(parent) {
  var table = $("<table/>");
  parent.append(table);
  return table;
}

function readData(parent) {
  var data = spData;
  var table = drawTable(parent);
  var rowData = [];

  for (var r = 0; r < data.length; r++) {
    var cell = data[r]["gs$cell"];
    var val = cell["$t"];
    if (cell.col == 1) {
      drawRow(table, rowData);
      rowData = [];
    }
    rowData.push(val);
  }
  drawRow(table, rowData);
}
$(document).ready(function () {
  readData($("#data"));
  searchTable('dragon', document.querySelector('table'));
});

function searchTable(searchStr, target) {
  let rows = Array.from(target.querySelectorAll('tr'));
  rows.forEach((row, idx, col) => {
    let firstCell = row.querySelector('td').textContent;
    if (firstCell == searchStr) {
      let cell2 = row.querySelectorAll('td')[1].textContent;
      console.log(`${searchStr} found in row ${idx}`);
      console.log(`col 2 of row #${idx} is: ${cell2}`);
    }
  });
}
...