gpt4 book ai didi

javascript - 如何在 PWA 中显示共享照片?

转载 作者:行者123 更新时间:2023-11-30 06:10:20 26 4
gpt4 key购买 nike

我已经成功地将我的 PWA 添加到我设备的共享选项中,问题是我不知道如何在我的 PWA 中接收/显示共享照片

manifest.json 中的 share_target

"share_target": {
"action": "/photos/shared",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"files": [{
"name": "file",
"accept": ["*/*"]
}]
}
}

我正在使用 CodeIgniter,所以我添加了 photos/shared 作为路径

$route['photos/shared']['post'] = 'webapp/PhotosController/sharedPhoto';

并期望在我的 Controller 中接收共享照片的发布数据

public function sharedPhoto () {

echo "<pre>";
die(var_dump( $_POST )); // empty!
echo "</pre>";

}

但是,不幸的是它是空的。

经过一番阅读,我发现了这个:

The foreground page cannot process this data directly. Since the page sees the data as a request, the page passes it to the service worker, where you can intercept it with a fetch event listener.

关于 this网站,所以我已将此代码添加到我的 service worker(我关注了 this tutorial )

self.addEventListener('fetch', function(event) {
if (event.request.clone().method === 'POST') {
const url = new URL(event.request.clone().url);
console.log( 'URL' );
console.log( url );
if (event.request.clone().url.endsWith('/photos/shared') || url.pathname == '/photos/shared') {
event.respondWith(Response.redirect('./'));

event.waitUntil(async function () {
const data = await event.request.formData();
console.log( data );
const client = await self.clients.get(event.resultingClientId);
console.log( client );
const file = data.get('file');
client.postMessage( {file});
}());
} else {
// do other non related stuff
}

之后,我将发布消息的事件监听器添加到我的 javascript 文件中

    navigator.serviceWorker.addEventListener('message', event => {
// this is triggered but file is always empty
const file = event.data.file;
const img = new Image();
const url = URL.createObjectURL(file);
img.src = url;
document.body.append(img);
});

但是,我就是无法在我的应用程序中显示图像,该文件始终为空。

最佳答案

好的, list 和服务 worker 的最新更改(我已经更新了我的问题)确实有效。我唯一需要做的就是更改消息事件监听器中的代码,以便能够看到图像。

navigator.serviceWorker.addEventListener('message', event => {

const file = event.data.file;
const img = new Image();
const url = URL.createObjectURL(file);
img.src = url;
$("body").empty();
$("body").append(img);
$("body").append(url);
$("body").append('<h1>test</h1>');

});

现在我可以在我的应用程序中访问照片,我终于可以对其执行必要的操作了。

关于javascript - 如何在 PWA 中显示共享照片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59269281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com