Skip to content

Add Android messaging integration #380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Apr 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 49 additions & 3 deletions inject/android.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,18 @@
* @module Android integration
* @category Content Scope Scripts Integrations
*/
import { load, init } from '../src/content-scope-features.js'
import { load, init, update } from '../src/content-scope-features.js'
import { processConfig, isGloballyDisabled } from './../src/utils'

const allowedMessages = [
'getClickToLoadState',
'getYouTubeVideoDetails',
'openShareFeedbackPage',
'setYoutubePreviewsEnabled',
'unblockClickToLoadContent',
'updateYouTubeCTLAddedFlag'
]

function initCode () {
// @ts-expect-error https://app.asana.com/0/1201614831475344/1203979574128023/f
const processedConfig = processConfig($CONTENT_SCOPE$, $USER_UNPROTECTED_DOMAINS$, $USER_PREFERENCES$)
Expand All @@ -16,10 +25,47 @@ function initCode () {
platform: processedConfig.platform
})

const messageSecret = processedConfig.messageSecret
// Receives messages from the platform
const messageCallback = processedConfig.messageCallback
// Sends messages to the platform
const messageInterface = processedConfig.messageInterface

const wrappedUpdate = ((providedSecret, ...args) => {
if (providedSecret === messageSecret) {
update(...args)
}
}).bind()

Object.defineProperty(window, messageCallback, {
value: wrappedUpdate
})

// @ts-ignore
const sendMessageToAndroid = window[messageInterface].process.bind(window[messageInterface])
delete window[messageInterface]

init(processedConfig)

// Not supported:
// update(message)
window.addEventListener('sendMessageProxy' + messageSecret, event => {
event.stopImmediatePropagation()

if (!(event instanceof CustomEvent) || !event?.detail) {
return console.warn('no details in sendMessage proxy', event)
}

const messageType = event.detail?.messageType
if (!allowedMessages.includes(messageType)) {
return console.warn('Ignoring invalid sendMessage messageType', messageType)
}

const message = {
type: messageType,
options: event.detail?.options
}
const stringifiedArgs = JSON.stringify(message)
sendMessageToAndroid(stringifiedArgs, messageSecret)
})
}

initCode()