Vue.js PWA中Web Share Target API的URL查询参数失效问题解决
Problem Scenario
I was building a new PWA with Vue.js and registered a Web Share Target in manifest.json. When directly entering a URL with query parameters (like "/#/page-edit?url=https://google.com/&title=Google&description=SearchEngine") in the browser address bar, the code worked perfectly—my Vue component could fetch parameters via this.$route.query without any issues.
But when sharing content through the Web Share Target API, the parameters never came through. I tried tweaking the manifest configuration (switching between GET/POST methods, adjusting enctype) but couldn't pin down if it was a config or code problem. My initial share_target config looked like this:
{ "action": "/#/page-edit", "method": "GET", "enctype": "application/x-www-form-urlencoded", "params": { "title": "title", "text": "description", "url": "url" } }
Root Cause Analysis
After digging deeper, I checked window.location.href and noticed the parameter placement was off: the shared parameters were appended before the hash fragment, like https://appurl.com/?title=xxx&description=xxx#/page-edit.
In Vue Router's default hash mode, the framework only parses the portion of the URL after the # as the route path and query. Since the Web Share Target was adding parameters before the #, Vue Router couldn't pick them up via $route.query.
Solution
The fix requires adjusting both your Vue Router setup and the manifest.json configuration:
Switch Vue Router to History Mode
Update your router initialization code to use history mode, which removes the hash fragment from URLs entirely:const router = new Router({ mode: 'history', routes: [ // Your route definitions here ] })Note: When using history mode, you'll need to configure your production server to redirect all requests to your
index.htmlfile (e.g., with Nginx'stry_filesdirective or Apache'sRewriteRule). This prevents 404 errors when users refresh pages directly.Update the Web Share Target Configuration
Remove the#from theactionfield in yourmanifest.jsonto match the history mode URL structure:{ "action": "/page-edit", "method": "GET", "enctype": "application/x-www-form-urlencoded", "params": { "title": "title", "text": "description", "url": "url" } }
After making these changes, the Web Share Target will append parameters directly to the page-edit route URL, and Vue Router can properly access them via this.$route.query just like when you manually enter the URL.
内容的提问来源于stack exchange,提问作者Jonatan Roose

