Getting TypeError: navigator.share error with Native Share using Stimulus and Rails

问题描述 投票:0回答:0

我正在使用带有 Rails 的 Stimulus 控制器为博客应用程序创建本地共享功能。

控制台确实记录了我想分享的标题和 URL,但是,当我单击“分享帖子”按钮时出现此错误:

Share error: TypeError: navigator.share is not a function

分享刺激控制器:

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="share"
export default class extends Controller {
  static targets = ["url", "title"];

  connect() {
    console.log("Connected to the share controller");
  }
  async share(e) {
    e.preventDefault();

    const shareData = {
      title: this.titleTarget.textContent,
      url: this.data.get("urlValue"),
    };
    console.log(shareData);
    try {
      await navigator.share(shareData);
    } catch (err) {
      console.error("Share error:", err)
      alert("Failed to share blog post")
    };
  }
 }

博客展示page.html.erb

<section class="mx-auto md:w-2/4 px-10 mb-20">
  <div class="bach-btn pb-4">
    <%= link_to "< back home", root_path, class: "no-underline text-center text-sm font-sans font-thin hover:text-lime-900 transition duration-400" %>
  </div>

  <div class="post-content" data-controller="share" data-share-url-value="<%= blog_post_url(@blog_post)%>" >
    <div class="post-title">
      <h1 class="text-lime-800 no-underline font-semibold text-2xl font-thin uppercase font-serif">
        <%= content_tag(:p, @blog_post.title, data: {
        share_target: "title"}) %> <%# # TITLE TARGET %>
      </h1>
      <p class="font-light text-xs italic pt-1 pb-4">Published: <%= time_ago_in_words(@blog_post.created_at) %></p>
    </div>

    <div class="post-body pb-10 font-thin">
      <p><%= @blog_post.content %></p>
    </div>
      <%= button_to "Share Post", "", data: {action: "click->share#share"} %>
      <%= render 'shared/blog_pagination' %>
  </div>
  <%= render 'shared/show_links' %>
</section>

我有点困惑我应该如何将它与正确的语法联系起来。非常感谢任何帮助。

谢谢

ruby-on-rails ruby-on-rails-4 stimulusjs
© www.soinside.com 2019 - 2024. All rights reserved.