[chrome:accessibility] Destruct accessibility event recorder after use.

Reset the accessibility event recorder pointer and the web contents
observer pointer rather than releasing them. This ensures that the
objects are destroyed, rather than just the reference to them released.
Also, stop the accessibility event recorder when destroying the
AccessibilityUIMessageHandler.

AX-Relnotes: Fix bug in chrome:accessibility page.

Bug: 785493, 1081469, 1043024, 1042569
Change-Id: I61ecc6cb12d3f9695130ca9c15900bf3070de1ff
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2199020
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Aaron Leventhal <[email protected]>
Commit-Queue: Abigail Klein <[email protected]>
Cr-Commit-Position: refs/heads/master@{#769846}
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc
index 2ef4d37..2d5ee33 100644
--- a/content/browser/web_contents/web_contents_impl.cc
+++ b/content/browser/web_contents/web_contents_impl.cc
@@ -3347,20 +3347,23 @@
 }
 
 void WebContentsImpl::RecordAccessibilityEvents(
-    AccessibilityEventCallback callback,
-    bool start) {
-  if (start) {
+    bool start_recording,
+    base::Optional<AccessibilityEventCallback> callback) {
+  // Only pass a callback to RecordAccessibilityEvents when starting to record.
+  DCHECK_EQ(start_recording, callback.has_value());
+  if (start_recording) {
     SetAccessibilityMode(ui::AXMode::kWebContents);
     auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
     DCHECK(ax_mgr);
     base::ProcessId pid = base::Process::Current().Pid();
     event_recorder_ = content::AccessibilityEventRecorder::Create(
         ax_mgr, pid, base::StringPiece{});
-    event_recorder_->ListenToEvents(callback);
+    event_recorder_->ListenToEvents(*callback);
   } else {
-    DCHECK(event_recorder_);
-    event_recorder_->FlushAsyncEvents();
-    event_recorder_ = nullptr;
+    if (event_recorder_) {
+      event_recorder_->FlushAsyncEvents();
+      event_recorder_.reset(nullptr);
+    }
   }
 }