asciidoctor / asciidoctor-browser-extension

:white_circle: An extension for web browsers that converts AsciiDoc files to HTML using Asciidoctor.js.
https://chrome.google.com/webstore/detail/asciidoctorjs-live-previe/iaalpfgpbocpdfblpnhhgllgbdbchmia
MIT License
219 stars 50 forks source link

Custom scripts should have access to the Asciidoctor processor #220

Open ggrossetie opened 6 years ago

ggrossetie commented 6 years ago

Now that we are using async, some work is done asynchronously. Previously we were using synchronous code with callbacks and the Asciidoctor's processor was registered as a global variable. Custom scripts were appended synchronously to the web page and could access this global variable. Now that custom scripts are appended asynchronously, we can't access this global variable anymore. However, while it was working, using a global variable was not a perfect solution.

EDIT: This is actually wrong, see below.

The Asciidoctor processor is defined in a content script and we need to find a solution to be able to register user defined extensions.

References:

ggrossetie commented 6 years ago

Actually I don't think it was working:

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

https://developer.chrome.com/extensions/content_scripts#execution-environment

Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts. However, content scripts get a "clean view of the DOM". This means: content scripts cannot see JavaScript variables defined by page scripts if a page script redefines a built-in DOM property, the content script will see the original version of the property, not the redefined version.

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#Content_script_environment

Since custom scripts are executed on the web page, they cannot call any functions or access any variables defined by content scripts.

As far as I understand, the only way to access the Asciidoctor's processor is to execute the custom scripts in the "content scripts" environment.

Firefox provides a very useful API to register content scripts: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/contentScripts/register

Unfortunately this API is only available in Firefox :disappointed:

The intermediate solution could be to use eval (but I don't think it's a good idea).