Share_Target을 통해 whatsapp에서 Angular 앱으로 이미지 공유가 작동하지 않음

Nov 16 2020

WhatsApp에서 내 앱으로 이미지를 공유하려고합니다. WhatsApp에서 내 앱으로 미디어 항목을 공유 할 때마다 웹 매니페스트 파일에 도달하고 / nav / emergencyRegister 경로를 대상으로합니다. WhatsApp에서 이미지를 공유하면 프런트 엔드에서 동일한 경로가 열리기 때문에 대상 경로로 이동할 것이라고 확신합니다.

다음은 내 manifest.webmanifest 파일의 코드입니다.

{
  "name": "Apoms",
  "short_name": "Apoms",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "gcm_sender_id": "275309609166",
  "share_target": {
    "action": "/nav/emergency-register",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "title": "name",
      "text": "description",
      "url": "link",
      "files": [
        {
          "name": "images",
          "accept": "image/*"
        },
        {
          "name": "videos",
          "accept": "video/*"
        }
      ]
    }
  }

그러나 EmergencyRegisterComponent.ts 파일에서 경로의 매개 변수에 있어야하는 이미지에 액세스하는 방법을 모릅니다.

다음은 Emergency-register-page.component.ts 파일의 코드입니다.

import { Component, OnInit } from '@angular/core';
import { PrintTemplateService } from '../../print-templates/services/print-template.service';
import { CaseService } from '../services/case.service';
import { EmergencyRegisterTabBarService } from '../services/emergency-register-tab-bar.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
    // tslint:disable-next-line:component-selector
    selector: 'emergency-register-page',
    templateUrl: './emergency-register-page.component.html',
    styleUrls: ['./emergency-register-page.component.scss'],
})
export class EmergencyRegisterPageComponent implements OnInit {
    constructor(private printService: PrintTemplateService,
        private route: ActivatedRoute,
        private caseServie: CaseService,
        private tabBar: EmergencyRegisterTabBarService) {}

    ngOnInit() {

        this.printService.initialisePrintTemplates();

// I printed the this.route and tried to find the image in there but failed.
// Also used params,querParams from route.
        const data = this.route.snapshot.paramMap.get('files');
        console.log(data);

    }
}

또한 여기 에서 기존 서비스 워커를 확장하려고했습니다 . 새 서비스 워커 파일 apoms-sw.js를 만들었습니다.

importScripts('./ngsw-worker.js');


self.addEventListener('fetch', event=>{
  console.log(event);
});

내 app.module.ts에서

@NgModule({
    declarations: [AppComponent, ConfirmationDialog, TreatmentRecordComponent],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        AppRoutingModule,
        MatDialogModule,
        NavModule,
        HttpClientModule,
        MaterialModule,
        ServiceWorkerModule.register('apoms-sw.js', { enabled: environment.production }),
        AngularFireDatabaseModule,
        AngularFireAuthModule,
        AngularFireMessagingModule,
        AngularFireStorageModule,
        AngularFireModule.initializeApp(environment.firebase)
    ],
    exports: [],
    providers: [
        DatePipe,
        { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true },
        // { provide: LOCALE_ID, useValue: 'it-IT' },
        { provide: ErrorHandler, useClass: UIErrorHandler }
    ],
    bootstrap: [AppComponent],
})

원격 디버깅 프로세스 중에 파일이 히트하고 있지만 가져 오기 이벤트 리스너를 실행하지 않는 것을 볼 수 있습니다. 그래서 누군가가 경로와 함께 오는 이미지에 액세스하는 방법을 알려줄 수 있다면. 그것은 좋은 것입니다.

답변

1 ArpitTrivedi Nov 30 2020 at 13:28

따라서 여기서 문제 중 하나는 Angular가 자체 서비스 워커를 생성한다는 것입니다. 그리고 애플리케이션은 하나의 서비스 워커 만 가질 수 있습니다. 이 질문 에서 더 많은 것을 읽을 수 있습니다 .

서비스 워커는 그들 중 하나가 respondWith를 호출 할 때까지 하나씩 중복 함수를 실행합니다. 그리고 원래 서비스 (ngsw-worker.js) 작업자에 의해 정의 된 가져 오기 함수에는 responseWith가 포함되어있어 더 이상 메시지가 전달되지 않습니다. 즉, ngsw-worker에서 fetch 함수를 실행하기 전에 모든 함수를 정의해야합니다. 이 질문 에서 더 많은 것을 읽을 수 있습니다 .

따라서 웹 매니페스트는 웹 매니페스트의 루트에 속하는 다음과 같아야합니다.

"share_target": {
    "action": "/nav/emergency-register",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "files": [
        {
          "name": "image",
          "accept": "image/*"
        },
        {
          "name": "video",
          "accept": "video/*"
        }
      ]
    }
  },

그런 다음 가져 오기 기능을 포함하고 서비스 워커를 가져올 새 파일이 필요합니다. 먼저 가져 오기 기능을 정의하는 것이 중요합니다.

self.addEventListener('fetch', event => {

  // Handle the share_target shares
  if (event.request.method === 'POST') {

    // Make sure we're only getting shares to the emergency-register route
    const path = event.request.url.split("/").pop();

    if(path === "emergency-register"){

        //Get the images and videos from the share request
        event.request.formData().then(formData => {

            // Find the correct client in order to share the results.
            const clientId = event.resultingClientId !== "" ? event.resultingClientId : event.clientId;
            self.clients.get(clientId).then(client => {

                // Get the images and video
                const image = formData.getAll('image');
                const video = formData.getAll('video');

                // Send them to the client
                client.postMessage(
                    {
                        message: "newMedia",
                        image: image,
                        video: video
                    }
                );
            });
        });
    }
  }
});


importScripts('./ngsw-worker.js');

그런 다음 app.component에서 게시 된 메시지를 포착 할 함수를 정의 할 수 있습니다. firebase 메시징 또는 클라이언트에 메시지를 게시하는 다른 함수를 사용하는 경우주의해야합니다. 어떻게 든 구분해야합니다.

// Set up to receive messages from the service worker when the app is in the background.
navigator.serviceWorker.addEventListener('message', (event:MessageEvent) => {

    if(event.data.hasOwnProperty('image')){

        this.emergencyTabBar.receiveSharedMediaItem(event.data);
    }

    if(event.hasOwnProperty('data')){

        this.messagingService.receiveBackgroundMessage(event.data?.firebaseMessaging?.payload);
   }

});