简体   繁体   English

使用 GWT 时未找到 Firebase Service Worker(404 错误)

[英]Firebase Service worker not found while using GWT (404 Error)

I'd like to use the firebase cloud messaging service in my GWT webapplication, but I'm stuck with some problems.我想在我的 GWT 网络应用程序中使用 firebase 云消息传递服务,但我遇到了一些问题。 The application should be able to register the firebase service worker and connect to the service with it's specific token.应用程序应该能够注册 firebase 服务工作者并使用它的特定令牌连接到服务。 This token, the received messages and the event when a token changes should be accessable in my GWT Java code.这个令牌、接收到的消息和令牌更改时的事件应该可以在我的 GWT Java 代码中访问。

The error occurs when I try to create the token by using handle.getToken().当我尝试使用 handle.getToken() 创建令牌时发生错误。 I get this error message:我收到此错误消息:

A bad HTTP response code (404) was received when fetching the script.
Failed to load resource: net::ERR_INVALID_RESPONSE

browserErrorMessage: "Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script." 
code: "messaging/failed-serviceworker-registration"
message: "Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. (messaging/failed-serviceworker-registration)."
stack: "FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. (messaging/failed-serviceworker-registration).↵    at https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js:41:225"__proto__: Error

The URL it tries to access to register the service worker is: http://127.0.0.1:11111/firebase-messaging-sw.js它尝试访问以注册 Service Worker 的 URL 是: http : //127.0.0.1 : 11111/firebase-messaging-sw.js

So it's obvious the problem is it tries to access the javascript from my local host address instead of the location where the other firebase JS files are.所以很明显问题是它试图从我的本地主机地址而不是其他 firebase JS 文件所在的位置访问 javascript。 So my question is how can I change that so it loads the file from the correct source?所以我的问题是如何更改它以便从正确的来源加载文件?

These scripts are included in my HTML file:这些脚本包含在我的 HTML 文件中:

<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyBxdZNXHiLR1IC8Wrw3Y6q_5DFoN8hn_UY",
    authDomain: "fir-test-848de.firebaseapp.com",
    databaseURL: "https://fir-test-848de.firebaseio.com",
    storageBucket: "fir-test-848de.appspot.com",
    messagingSenderId: "974661154941"
  };
  firebase.initializeApp(config);
</script>

This is my Java code:这是我的Java代码:

public class FireBase
{

    private JavaScriptObject _messagingHandle;
    private String _token;

    public FireBase()
    {
        _messagingHandle = createMessagingHandle();
        requestPermission(_messagingHandle, this);
    }

    private native JavaScriptObject createMessagingHandle()
    /*-{
        return $wnd.firebase.messaging();
    }-*/;

    private native void listenTokenRefresh(final JavaScriptObject handle)
    /*-{
        handle.onTokenRefresh(function()
        {
            instance.@x.client.miscellaneous.FireBase::onTokenRefresh()();
        });
    }-*/;

    private void onTokenRefresh()
    {
        getToken(_messagingHandle, this);
    }

    private native void requestPermission(final JavaScriptObject handle, final Object instance)
    /*-{
        handle.requestPermission().then(function()
        {
            $wnd.console.log('Notification permission granted.');
            instance.@x.client.miscellaneous.FireBase::onPermission(Z)(true);
        })
    }-*/;

    private void onPermission(final boolean granted)
    {
        if (granted)
        {
            getToken(_messagingHandle, this);
        }
    }

    private native void getToken(final JavaScriptObject handle, final Object instance)
    /*-{
        handle.getToken().then(function(currentToken)
        {
            if (currentToken)
            {
                instance.@x.client.miscellaneous.FireBase::onTokenReceived(Ljava/lang/String;)(currentToken);
            }
            else
            {
                // Show permission request.
                $wnd.console.log('No Instance ID token available. Request permission to generate one.');
                instance.@x.client.miscellaneous.FireBase::onTokenReceived(Ljava/lang/String;)(null);
            }
        })

    }-*/;

    private void onTokenReceived(final String token)
    {
        if (token != null)
        {
            GWT.log("Received Token: " + token);
            if (!token.equals(_token))
            {
                // Send/Update token to server
            }
        }
    }
}

只需在根文件夹 firebase-messaging-sw.js 中创建一个空文件

The Firebase SDK attempts to register the service worker at a specific location. Firebase SDK 尝试在特定位置注册服务工作线程。

The location is + /firebase-messaging-sw.js.位置是 + /firebase-messaging-sw.js。 There are two options:有两种选择:

1.) Make + /firebase-messaging-sw.js work in the browser (ie make sure it returns a valid response) and then try using the SDK again (it should work if the browser can access the file). 1.) 让 + /firebase-messaging-sw.js 在浏览器中工作(即确保它返回一个有效的响应),然后再次尝试使用 SDK(如果浏览器可以访问该文件,它应该可以工作)。

2.) Use the useServiceworker(<service worker registration>) method to pass in a custom service worker. 2.) 使用useServiceworker(<service worker registration>)方法传入自定义的 service worker。 This will still require you to have a valid service worker URL.这仍然需要你有一个有效的 service worker URL。

Check your angular cli file ... add检查您的角度 cli 文件...添加

"firebase-messaging-sw.js", "manifest.json" "firebase-messaging-sw.js", "manifest.json"

"assets": [ "assets", "app/main/content/components/angular-material", "favicon.ico", "firebase-messaging-sw.js", "manifest.json" ], "assets": [ "assets", "app/main/content/components/angular-material", "favicon.ico", "firebase-messaging-sw.js", "manifest.json"],

Not only a empty file, is a good idea to add the content like:不仅是一个空文件,添加如下内容也是一个好主意:

    importScripts('https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.14.2/firebase-messaging.js');
/*Update this config*/
var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = payload.data.title;
  const notificationOptions = {
    body: payload.data.body,
    icon: 'http://localhost/gcm-push/img/icon.png',
    image: 'http://localhost/gcm-push/img/d.png'
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});
// [END background_handler]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM