расширение Chrome для изменения шрифта - PullRequest
0 голосов
/ 20 марта 2019

У меня проблемы с доступом к DOM при попытке написать расширение Chrome для изменения шрифта.Я продолжаю получать сообщение об ошибке: «Ошибка в обработчике события: Ошибка типа: Не удается прочитать свойство 'executeScript' из неопределенного» * ​​1001 *

Я пытался сделать то, что ответ этого стекового потока говорит, но это не 'Т работал на меня.Я также пытался следовать документации Chrome Extension для сценариев содержимого.

Я могу успешно передать свое сообщение из всплывающего сценария в сценарий содержимого.При выполнении console.log (document) он дает мне DOM, который я хочу редактировать.

Вот мой всплывающий скрипт:

function sendArial() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          chrome.tabs.sendMessage(tabs[0].id, {data : "arial"}, function(response) {
            console.log('success');
        });
    })};

function sendGeorgia() { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {data : "georgia"}, function(response) {
            console.log('success');
        });
    })};


function sendHelvetica() { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {data : "helvetica"}, function(response) {
            console.log('success');
        });
    })};

function sendTimeNewRoman() { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {data : "times new roman"}, function(response) {
            console.log('success');
        });
    })};

arial.addEventListener('click', sendArial);
georgia.addEventListener('click', sendGeorgia);
helvetica.addEventListener('click', sendHelvetica);
timesnewroman.addEventListener('click', sendTimeNewRoman);

Вот мой сценарий содержания:

chrome.runtime.onMessage.addListener(
  function(request) {
    if (request.data == "arial") {
      console.log('success! arial');
      console.log(document);
      chrome.tabs.executeScript(
          {file: 'arial.js'});
    }
    else if (request.data == "georgia"){
      console.log('success! georgia');
      console.log(document);
      chrome.tabs.executeScript(
          georgiaFontStyle()
        );
    }
    else if (request.data == "helvetica") {
      console.log('success! helvetica');
      console.log(document);
      helveticaFontStyle();
    }
    else if (request.data == "times new roman"){
      console.log('success! times');
      console.log(document);
      timesNewRomanFontStyle();
    }
  });
  
  function georgiaFontStyle() {
  var p = document.querySelectorAll("p");
  var textStyle = p.style;
  textStyle.cssText = 'font-family: Georgia; font-size: 20px; line-height: 1.45;';
  textStyle.margin = '0 auto';
  textStyle.width = '35em';
}

function helveticaFontStyle() {
  var p = document.querySelectorAll("p");
  var textStyle = p.style;
  textStyle.cssText = 'font-family: Helvetica Neue; font-size: 20px; line-height: 1.45;';
  textStyle.margin = '0 auto';
  textStyle.width = '35em';
}

function timesNewRomanFontStyle() {
  var p = document.querySelectorAll("p");
  var textStyle = p.style;
  textStyle.cssText = 'font-family: Times New Roman; font-size: 20px; line-height: 1.45;';
  textStyle.margin = '0 auto';
  textStyle.width = '35em';
}

А вот скрипт arial.js, который вызывается в скрипте содержимого:

function arialFontStyle() {
p = document.querySelectorAll("p");
textStyle = p.style;
textStyle.cssText = 'font-family: Arial; font-size: 20px; line-height: 1.45;';
textStyle.margin = '0 auto';
textStyle.width = '35em';
}

Я оставил функции в скрипте содержимого и сохранил варианты их вызова, чтобы продемонстрировать проблему этого типа.Для случая helveticaFontStyle () и timesNewRomanFontStyle () сообщение об ошибке гласит «Ошибка в обработчике события: TypeError: Невозможно установить свойство« cssText »из неопределенного» * ​​1032 *

И arialFontSelection (), и georgiaFontSelection () дают мне: «Ошибка в обработчике события: TypeError: Невозможно прочитать свойство executeScript» undefined »

Вот репозиторий github, более или менее такой же.https://github.com/smcalilly/gutenberg-typography

Пожалуйста, помогите!Спасибо.

...