0

Приветствую!

Есть проблема с webExtension в firefox. По идее всё отлично работает, только вот я не могу передать нужные мне данные в офис. sendNativeMessage() по мануалу сказано, что передаёт сообщение внешней программе, в моём случае должен открыться libreoffice с сообщением: "message!". А в итоге получаю как на картинке ниже. т.е. он выводит openoffice.json, а не то сообщение что мне нужно. Буду рад любой помощи!)

P.S. то что закомментированно в script.js - так можно было пускать офис в старом API extensions firefox.

background.js:

function onResponse(response) {
    console.log(`Received ${response}`);
}

function onError(error) {
    console.log(`Error: ${error}`);
}

function connected(p) {
   console.log('connected');
   browser.runtime.sendNativeMessage("openoffice", {message:"message!"})
     .then(onResponse, onError);
}

browser.runtime.onConnect.addListener(connected);

script.js:

function onError(error) {
  console.log(`Error: ${error}`);
}

function onGot(item) {
  var color = "blue";
  if (item.color) {
     color = item.color;
  }
  document.body.style.border = "10px solid " + color;
}

var getting = browser.storage.local.get("color");
getting.then(onGot, onError);

function action(event) {
  findOOo(event);
  browser.runtime.onMessage.removeListener(action);
}

function findOOo(event) {
  event.target.innerHTML = "link name is changed";
  // let port = browser.runtime.connectNative("C:\\Program Files\\LibreOffice 5\\program\\soffice.exe");
  var myPort = browser.runtime.connect({name:"port-from-cs"});

  // var file = Components.classes["@mozilla.org/file/local;1"].getService(Components.interfaces.nsILocalFile);
 // var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
 // var soffice = "C:\\Program Files\\LibreOffice 5\\program\\soffice.exe";
 // file.initWithPath(soffice);
 // process.init(file);
 // var args = [event.target.href];
 // process.run(false, args, args.length);
 // event.stopPropagation();
 // return false;
}

function hasClass(elem, className) {
  return /.*OOo.*/.test(elem.className);
}

document.addEventListener("click", function(event) {
  if (hasClass(event.target)) {
     action(event);
  }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "OpenOffice for I.Q.P.H.A.R.M",
  "description": "Allows to edit OpenOffice docs with help webdav protocol",
  "version": "1.0",
  "applications": {
    "gecko": {
       "id": "[email protected]",
       "strict_min_version": "50.0"
    }
  },
  "icons": {
    "48": "icons/icon.png"
  },
  "background": {
    "scripts": ["content_scripts/background.js"]
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content_scripts/script.js"]
  }],
  "options_ui": {
    "page": "settings/options.html"
  },
  "permissions": [
    "storage",
    "nativeMessaging",
   "tabs",
   "activeTab"
  ]
}

openoffice.json(добавлен в реестр):

{
  "name": "openoffice",
  "description": "Connector to local editor openoffice for downloaded file",
  "path": "C:\\Program Files\\LibreOffice 5\\program\\soffice.exe",
  "type": "stdio",
  "allowed_extensions": ["[email protected]"]
}

результат работы плагина

1 ответ 1

0

В итоге, вместо прямого вызова soffice.exe пришлось написать python скрипт который открывает офис и получает от плагина postMessage.

openoffice.py:

import struct, sys, subprocess, json, logging
def getMessage():
  rawLength = sys.stdin.buffer.read(4)
  if len(rawLength) == 0:
      sys.exit(0)
  messageLength = struct.unpack('@I', rawLength)[0]
  message = sys.stdin.buffer.read(messageLength).decode('utf-8')
  return json.loads(message)
while True:
   args = getMessage()
   subprocess.call(args['office'] + ' ' + args['link'], args['len'])

background.js:

function connected(port) {
   port.onMessage.addListener(function(messageFromCS) {
      let port = browser.runtime.connectNative("openoffice");
      port.postMessage({"office":messageFromCS.pathToOffice, "link":messageFromCS.link, "len":1});
   });
}

browser.runtime.onConnect.addListener(connected);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.