weboffice获取外部剪切板内容解决方案

1、初始化引入sdk时,需要传入监听函数  --  getClipboardData

在移动端 APP 需要从系统剪切板获取数据时,可以使用该接口。

目前仅支持移动端表格以及文字,并且 JSSDK 版本为 v1.1.6

可以通过传入 获取系统剪切板数据函数 在文档粘贴的时候,调用传入函数获取系统剪切板数据,返回一个 Promise 或者 Object

// 获取系统剪切板数据函数
const getClipboardData = () => {
  // 自身业务处理……

  return Promise.resolve({
    text: 'xxx', // text 格式数据
    html: 'xxx', // html 格式数据,目前仅表格支持
    updateExternal: true // 是否从外部粘贴数据,为 false 则从内部剪切板获取
  })
}

// 配置获取系统剪切板数据函数
WebOfficeSDK.init({
  officeType: WebOfficeSDK.OfficeType.Writer,
  appId: 'xxxxx',
  fileId: 'xxxxx',
  getClipboardData
})

解决方案一:

通过window.navigator.clipboard.read()读取浏览器剪切板内容,不过浏览器安全限制,需要先弹窗是否有读取权限,可以通过window.navigator.permissions.query来判断浏览器是否有权限读取

代码

export async function getClipboardText() {
    const name = await window.navigator.permissions.query({
      name: 'clipboard-read'
    })
    const clipboardItems = await window.navigator.clipboard.read()
    let textHtml, textPlain
    for (const clipboardItem of clipboardItems) {
      for (const type of clipboardItem.types) {
        const item = await clipboardItem.getType(type)
        if (item && item.type === 'text/html') {
          textHtml = await item.text()
        }
        if (item && item.type === 'text/plain') {
          textPlain = await item.text()
        }
      }
    }
    console.log(textPlain)
    return { textHtml, textPlain }
}

调用

const getClipboardData = () => {
      return new Promise((resolve)=>{
        getClipboardText().then(res=>{
           resolve({
              text:res.textPlain,
              html:res.textHtml,
              updateExternal: true, 
            })
        });
      })
    };

!!!限制:很多手机浏览器不支持,无法弹出是否获取剪切板权限,目前只在pc谷歌浏览器调试成功

解决方案二:安卓开发同学自己去监听剪切板内容是否变化,在前端提供一个js方法让安卓端来调用,通过这种方式来改变获取到的剪切板内容。

vue中提供的js调用方法

mounted(){
    window.getText = this.getText;
},
methods:{
    // 安卓端调用函数传入剪切板内容
    getText(data){
      this.textPlain = data;
    }
}

getClipboardData函数初始化

const getClipboardData = () => {
      return new Promise((resolve)=>{
        console.log(this.textHtml, this.textPlain)
        resolve({
          text:this.textPlain,
          html:this.textHtml,
          updateExternal: true, 
        })
      })
    };

!!!注意

需要加入文字监听事件和表格监听事件 

 代码

 jssdk.ApiEvent.AddApiEventListener('ClipboardCopy', data => {
        this.textPlain = data.text
        console.log(this.textPlain);
      })
      jssdk.ApiEvent.AddApiEventListener('Clipboard_Copy', data => {
        this.textPlain = data.text;
      })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值