Skip to content

Commit

Permalink
Wire up content script
Browse files Browse the repository at this point in the history
- Observe messages and check sentiment of all
  whenever the DOM changes
- Try to load model as quickly as possilbe
  unfortunately this is still slow and blocking
  • Loading branch information
WalternativE committed Nov 18, 2020
1 parent 3678035 commit a515ab9
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 22 deletions.
58 changes: 57 additions & 1 deletion contentScript.js
Original file line number Diff line number Diff line change
@@ -1 +1,57 @@
console.log("Hello from content script!");
const disclaimerLine = "⚡⚡⚡BEWARE THIS WAS MOST LIKELY RUDE AND HAS BEEN SILENCED⚡⚡⚡ "

const checkForToxicity = (text, node) => {
chrome.runtime.sendMessage({ statement: text },
function (response) {
console.log(response);
if (response.sentimentResult.toxic) {
node.innerHTML = disclaimerLine;
}
});
};

setTimeout(() => {
// we crash and burn if we do this right away so we wait for two seconds
console.log('Starting after 2000 millis');

const checkAllVisibleMessages = () => {
const dmSpans = document.querySelectorAll('div[role="presentation"] div span');

dmSpans.forEach(span => {
const text = span.innerText;
// very meager hack against endless recursion and emoji spans
if (!text.startsWith(disclaimerLine) && text.length > 1) {
console.log(text);
checkForToxicity(text, span);
}
});
};

checkAllVisibleMessages();

// Because we need to watch the page we use Mutation Observers
// I lifted this directly from MDN 💪
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// Select the node that will be observed for mutations
const targetNode = document.body;

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function (mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
checkAllVisibleMessages();
}
}
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);
}, 2000);
14 changes: 12 additions & 2 deletions src/Silencer.Extension.Background/Main.fs
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,31 @@ open Microsoft.JSInterop
open Silencer.Extension.Shared.Predictor
open Silencer.Extension.Shared.Types

[<Struct>]
type Result =
{ toxic: bool
confidence: float32 }

type MyApp() =
inherit Component()

do printfn "MyApp component created"

override this.OnInitialized() = printfn "On Initialized"

override this.OnInitializedAsync() =
printfn "On Initialized Async"
predictToxicity "start up the works" |> ignore
Task.CompletedTask

override this.Render() =
printfn "Loaded program"
empty

[<JSInvokable>]
static member NotifyFromBackgroundJs (message: string): Task<string> =
static member NotifyFromBackgroundJs (message: string): Task<Result> =
printfn $"I was called from the background js with the message %s{message}. Long live interop!"
let prediction = predictToxicity message
let normalizedConfidence = if prediction.Prediction then prediction.Probability else 1F - prediction.Probability

Task.FromResult($"Toxic: %b{prediction.Prediction} Confidence: %f{normalizedConfidence}")
Task.FromResult({ toxic = prediction.Prediction; confidence = normalizedConfidence})
18 changes: 1 addition & 17 deletions src/Silencer.Extension.Background/wwwroot/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,3 @@
chrome.runtime.onInstalled.addListener(function () {
chrome.storage.sync.set({ color: '#3aa757' }, function () {
console.log('Hello from within the background');
});

chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
pageUrl: { hostEquals: 'developer.chrome.com' },
})
],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});

chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(sender.tab ?
Expand All @@ -22,7 +6,7 @@ chrome.runtime.onMessage.addListener(
if (request.statement) {
console.log(`Got a message saying ${request.statement}. Attempting to call dotnet function.`)
DotNet.invokeMethodAsync('Silencer.Extension.Background', 'NotifyFromBackgroundJs', request.statement)
.then(m => sendResponse({ farewell: m }));
.then(m => sendResponse({ sentimentResult: m }));

return true;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Silencer.Extension.Frontend/Main.fs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ let update (js: IJSRuntime) message model =
{ model with TextToPredict = text }, Cmd.none
| PredictToxicity ->
let cmd =
Cmd.OfJS.attempt js "sendGreeting" [| model.TextToPredict |] Error
Cmd.OfJS.attempt js "sendStatement" [| model.TextToPredict |] Error

model, cmd
| Error exn ->
Expand Down
2 changes: 1 addition & 1 deletion src/Silencer.Extension.Frontend/wwwroot/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
window.sendGreeting = (statement) => {
window.sendStatement = (statement) => {
chrome.runtime.sendMessage({ statement },
function (response) {
console.log(response);
Expand Down

0 comments on commit a515ab9

Please sign in to comment.