実現したいこと
マウスでドラッグした単語をショートカットキーでググれるようにしたい。(新しいタブで)
この機能を正常に実装出来るようにしたい。
発生している問題・分からないこと
エラーメッセージ
error
1Uncaught TypeError: Cannot read properties of undefined (reading 'addListener') 2コンテキスト 3background.js 4スタック トレース 5background.js:1 (無名関数) 6 7Uncaught TypeError: chrome.extension.sendMessage is not a function 8コンテキスト 9https://www.hanamaruudon.com/ 10スタック トレース 11content.js:2 (無名関数) 12 13Uncaught SyntaxError: Unexpected token '<' 14コンテキスト 15background.js 16スタック トレース 17background.js:1 (無名関数)
該当のソースコード
background.js
1chrome.action.onClicked.addListener((tab) => { 2 chrome.scripting.executeScript({ 3 target: { tabId: tab.id }, 4 function: functionToInject 5 }); 6}); 7 8function functionToInject() { 9 document.addEventListener('keydown', function(event) { 10 if (event.ctrlKey && event.shiftKey && event.code === 'KeyF') { 11 const selectedText = window.getSelection().toString(); 12 if (selectedText) { 13 const url = 'https://www.google.com/search?q=' + encodeURIComponent(selectedText); 14 window.open(url, '_blank'); 15 } 16 } 17 }); 18} 19
contents.js
1document.addEventListener('keydown', function(event) { 2 if (event.ctrlKey && event.shiftKey && event.code === 'KeyF') { 3 const selectedText = window.getSelection().toString(); 4 if (selectedText) { 5 const message = { 6 text: selectedText 7 }; 8 chrome.runtime.sendMessage(message, function(response) { 9 console.log(response); 10 }); 11 } 12 } 13}); 14
manifest.json
1{ 2 "manifest_version": 3, 3 "name": "Word Search", 4 "version": "1.0", 5 "permissions": ["activeTab"], 6 "background": { 7 "service_worker": "background.js" 8 }, 9 "action": {}, 10 "content_scripts": [ 11 { 12 "matches": ["<all_urls>"], 13 "js": ["content.js"] 14 } 15 ], 16 "icons": { 17 "16": "images/icon16.png", 18 "48": "images/icon48.png", 19 "128": "images/icon128.png" 20 } 21} 22
popup.html
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7</head> 8<body> 9 10</body> 11<script src="content.js"></script> 12<script src="background.js"></script> 13</html> 14 15
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
自分なりにソースコードを改変したが同じエラーが出続けた。teratailに同じような質問があったが未解決だった。
補足
VScode,win11

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2024/04/11 07:42