简体   繁体   English

通过 Share_Target 将图像从 whatsapp 共享到 angular 应用程序不起作用

[英]Sharing images from whatsapp to angular app via Share_Target not working

I am trying to share images from WhatsApp to my app.我正在尝试将 WhatsApp 中的图像共享到我的应用程序。 Whenever I share a media Item from WhatsApp to my app it hits the webmanifest file and targets the /nav/emergencyRegister route.每当我将媒体项目从 WhatsApp 共享到我的应用程序时,它都会访问 webmanifest 文件并定位到 /nav/emergencyRegister 路由。 I am sure it's going to the target route because when I share an image from WhatsApp it opens the same route in the front end.我确信它会到达目标路线,因为当我从 WhatsApp 共享图像时,它会在前端打开相同的路线。

Here is the code from my manifest.webmanifest file.这是我的 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/*"
        }
      ]
    }
  }

But in the EmergencyRegisterComponent.ts file, I don't know how to access the image Which should be in the parameters of the route.但是在EmergencyRegisterComponent.ts文件中,我不知道如何访问应该在路由参数中的图像。

Here is my code from the emergency-register-page.component.ts file.这是我来自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);

    }
}

I also tried to extend the existing service worker from here .我还尝试从这里扩展现有的 service worker。 I created a new service worker file apoms-sw.js我创建了一个新的 service worker 文件 apoms-sw.js

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


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

In my app.module.ts在我的 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],
})

I can see that the file is being hit while the remote debugging process but it's not firing the fetch event listener.我可以看到在远程调试过程中文件正在被命中,但它没有触发 fetch 事件侦听器。 So if anyone can tell me how I can access the image which is coming with the route.因此,如果有人能告诉我如何访问路线附带的图像。 It would be great.那会很好。

So one of the issues here is that Angular creates its own service worker.所以这里的问题之一是 Angular 创建了自己的 service worker。 And an application can only have one service worker.一个应用程序只能有一个 Service Worker。 You can read more about it in this question.你可以在这个问题中阅读更多关于它的信息。

Service workers fire duplicate functions one after the other until one of them calls respondWith.服务工作者一个接一个地触发重复的函数,直到其中一个调用 responseWith。 And the fetch function defined by the original service (ngsw-worker.js) worker has a respondWith in it, meaning that no further messages are passed on.由原始服务 (ngsw-worker.js) 工作人员定义的 fetch 函数在其中有一个 responseWith,这意味着不再传递任何消息。 This means you need to define any functions before the fetch function in the ngsw-worker fire.这意味着您需要在 ngsw-worker fire 中的 fetch 函数之前定义任何函数。 You can read more in this question.您可以在问题中阅读更多内容。

So the webmanifest should look like this, which belongs in the root of your webmanifest:所以 webmanifest 应该看起来像这样,它属于你的 webmanifest 的根目录:

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

And then you need a new file that will contain your fetch function and import the service worker.然后你需要一个包含你的 fetch 函数并导入 service worker 的新文件。 It is important to define your fetch function first:首先定义您的 fetch 函数很重要:

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');

Then in your app.component you can define the function that will catch the posted message, be careful if you are using firebase messaging or other functions that post messages to the client, you'll need to differentiate between them somehow:然后在您的 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);
   }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试通过whatsapp共享链接时,收到消息**共享失败,请重试** - getting message **sharing failed please try again** in ionic app when I try to share link via whatsapp 离子电容器共享插件不与whatsapp共享图像 - ionic capacitor share plugin not sharing image with whatsapp 从 Angular 2 Web 应用程序发送 whatsapp 消息 - send whatsapp message from angular 2 web app 当我在 WhatsApp 上分享链接时,动态添加的元标记不显示图像、描述和标题。 (角 2) - Dynamically added meta tags are not showing images, description and title when I share a link on WhatsApp. (Angular 2) 如何在我的angular(6+)PWA应用中带来共享选项,以将媒体共享到社交应用(Messenger,Whatsapp)? - How can i bring share option in my angular(6+) PWA app to share media to social apps(Messenger,Whatsapp)? 在Angular 2中使用ng2共享按钮进行共享 - Sharing using ng2 share buttons in Angular 2 从 Contenful + Angular 应用程序中的条目渲染图像 - Render images from Entries in Contenful + Angular app 在 Angular 应用程序中显示来自 Clearbit 的图像 - Display Images from Clearbit in Angular App WebShare API 未在 iOS 上共享图像:Angular - WebShare API not sharing images on iOS: Angular 来自应用程序组件的 CSS 在 Angular 应用程序中不起作用 - CSS from app component is not working in Angular app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM