Skip to content

Commit

Permalink
feat(extensions): support Scratch Link 2.0 browser extension
Browse files Browse the repository at this point in the history
Right now this is only needed for Safari
  • Loading branch information
cwillisf committed Aug 16, 2022
1 parent 22f89ed commit 2bdea91
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/engine/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,8 @@ class Runtime extends EventEmitter {
* @type {?string}
*/
this.origin = null;

this._initScratchLink();
}

/**
Expand Down Expand Up @@ -1437,6 +1439,27 @@ class Runtime extends EventEmitter {
(result, categoryInfo) => result.concat(categoryInfo.blocks.map(blockInfo => blockInfo.json)), []);
}

/**
* One-time initialization for Scratch Link support.
*/
_initScratchLink () {
/* global globalThis */
// Check if we're actually in a browser
if (globalThis.document && document.getElementById) {
// Create a script tag for the Scratch Link browser extension, unless one already exists
const scriptElement = document.getElementById('scratch-link-extension-script');
if (!scriptElement) {
const script = document.createElement('script');
script.id = 'scratch-link-extension-script';
document.body.appendChild(script);

// Tell the browser extension to inject its script.
// If the extension isn't present or isn't active, this will do nothing.
globalThis.postMessage('inject-scratch-link-script', globalThis.origin);
}
}
}

/**
* Get a scratch link socket.
* @param {string} type Either BLE or BT
Expand All @@ -1462,7 +1485,11 @@ class Runtime extends EventEmitter {
* @returns {ScratchLinkSocket} The new scratch link socket (a WebSocket object)
*/
_defaultScratchLinkSocketFactory (type) {
return new ScratchLinkWebSocket(type);
const Scratch = self.Scratch;
const ScratchLinkSafariSocket = Scratch && Scratch.ScratchLinkSafariSocket;
// detect this every time in case the user turns on the extension after loading the page
const useSafariSocket = ScratchLinkSafariSocket && ScratchLinkSafariSocket.isSafariHelperCompatible();
return useSafariSocket ? new ScratchLinkSafariSocket(type) : new ScratchLinkWebSocket(type);
}

/**
Expand Down

0 comments on commit 2bdea91

Please sign in to comment.