"sync is not defined" error showing in chrome extension - google-chrome

sync is not defined" error showing in chrome extension while have used storage permission.please acknowledge me where is error and how
will solve message : "sync is not defined" stack : "ReferenceError:
sync is not defined↵ at eval (eval at
(http://localhost:46950/app/popup.js:31:9), :1:1)↵ at
HTMLInputElement.
(http://localhost:46950/app/popup.js:31:9)↵ at
HTMLInputElement.dispatch
(http://localhost:46950/app/img/jquery-3.2.1.min.js:6:12417)↵ at
HTMLInputElement.q.handle
//manifest.json
{
"manifest_version": 2,
"name": "One-click ",
"description": "This extension demonstrates a browser .",
"version": "1.0",
"app": {
"launch": {
"local_path": "popup.html"
}
},
"browser_action": {
"default_icon": "img/icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [ "popup.js", "img/jquery-3.2.1.min.js" ],
"persistent": false
},
"content_scripts": [
{
"css": [ "img/bootstrap.min.css"],
"js": [ "app/popup.js", "img/jquery-3.2.1.min.js" ],
"matches": [ "http://*/*", "https://*/*" ]
}
],
"permissions": [
"activeTab",
"storage",
"tabs",
"identity"
]
}
//popup.js
chrome.storage.sync.set({ 'data':"helloset" }, function () {
alert("saved");
});

*method* is not defined errors usually means the method was being called while the library wasn't yet loaded or there's really no such method. In your case, I think it's the former. Looking at the IzumiSy/manifest.json sync example, you need to use document.body.onload first then call that function like:
// popup.js
document.body.onload = function() {
chrome.storage.sync.get("data", function(items) {
if (!chrome.runtime.error) {
console.log(items);
document.getElementById("data").innerText = items.data;
}
});
}

if you need to save data locally you can use
document.body.onload = function() {
chrome.storage.sync.get("data", function(items) {
if (!chrome.runtime.error) {
console.log(items);
document.getElementById("data").innerText = items.data;
}
});
}
document.getElementById("set").onclick = function() {
var d = document.getElementById("text").value;
chrome.storage.sync.set({ "data" : d }, function() {
if (chrome.runtime.error) {
console.log("Runtime error.");
}
});
window.close();
}

Related

Chrome extension error "runtime.lastError: The message port closed before a response was received. "

I am buidng a chrome app to click a element after pageloaded :
manifest.json:
{
"manifest_version": 2,
"name": "click chapter-btn",
"version": "1.0",
"browser_action":{ },
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"storage",
"https://www.youtube.com/*"
],
"content_scripts": [
{
"matches": ["https://www.youtube.com/*"],
"all_frames": true,
"js": ["contentScript.js"]
}
]
}
contentscript.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(document.readyState !== 'complete') {
window.addEventListener('load',afterWindowLoaded);
} else {
afterWindowLoaded();
}
function afterWindowLoaded(){
setTimeout(()=>{
var btn = document.querySelector('.ytp-chapter-title-prefix')
btn?.click()
},3000)
}
return true
});
background.js:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo && changeInfo.status == "complete"){
if(!tab.url.includes('https://www.youtube.com/watch')){
return
}
chrome.tabs.sendMessage(tabId, {data: tab}, function(response) {});
}
});
I searched some solutions in internet, 'add "return true" to chrome.runtime.onmessage listener',but still show this error, Dont know what to do.

Cannot Send Message from Popup to Content

I want to send message from Popup.js into Content script by this code:
popup.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { xpath: xpath });
});
And Receive it in Content Script by this code:
content.js
chrome.runtime.onMessage.addListener(gotMessage());
function gotMessage(request, sender, sendResponse) {
alert("Hello");
}
My Manifest is:
manifest.json
{
"manifest_version": 2,
"name": "Auto Clicker",
"description": "Set Time, Set Element to Click, Start!",
"version": "0.1",
"permissions": ["tabs", "<all_urls>"],
"browser_action": {
"default_icon": {
"16": "images/icon-16x16.png",
"24": "images/icon-24x24.png",
"32": "images/icon-32x32.png"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"default_title": "Auto Clicker",
"default_popup": "popup.html"
},
"icons": {
"16": "images/icon-16x16.png",
"24": "images/icon-24x24.png",
"32": "images/icon-32x32.png",
"128": "images/icon-128x128.png"
}
}
Why it is not Working? the messages is'nt send to the Content script.
My issue is solved in this way:
// Inject Trigger to the current active Web Page
function injectTheScript() {
let xpath = document.getElementById("xpath-input").value || "";
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.executeScript({
code: `
(function () {
let btn = new XPathEvaluator()
.createExpression("${xpath}")
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue;
btn.click();
})();
`
});
});
}

Cannot read property 'onBoundsChanged' of undefined

When I write a extension for google chrome I got error as title question. Below is my code:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, {
file: "libs/jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "src/content.js"
});
});
});
chrome.app.window.onBoundsChanged.addListener(function (tab) {
chrome.tabs.executeScript(null, {
file: "libs/jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "src/content.js"
});
});
});
Firstly, I got success with onClicked event. But I want extension work when I resized window. But when I add 2nd event. Error occur
Please help me this error
Thank you
manifest.json
{
"name": "Bootstrap Grid for any Website",
"version": "1.1.0",
"manifest_version": 2,
"description": "Quickly toggle a Bootstrap Grid for any website. Easy to use, easy success.",
"browser_action": {
"default_icon": "src/icon48.png"
},
"background" : {
"scripts" : [
"src/background.js"
]
},
"content_scripts": [
{
"js": [ "src/send_value.js" ],
"matches": [ "<all_urls>" ],
"all_frames": true,
"run_at": "document_end"
}
],
"permissions": ["activeTab"]
}
I think you've mixed up chrome extensions and chrome apps. As we can read here, chrome.app.window is
not associated with any Chrome browser windows
I recommend you create content.js script where you put something like this:
window.addEventListener('resize', function(e){
....
// here you send message to background.js
var message = { info: "window resized");
chrome.runtime.sendMessage( "", message );
})
content.js must be executed in every tab you specified in manifest file.
In your background.js you should write:
chrome.runtime.onMessage.addListener(function(message){
if(message.info === "window resized"){
chrome.tabs.executeScript(null, // ..... the stuff you've written above
......
}
});
Links:
chrome.runtime.sendMessage
chrome.runtime.onMessage
Good luck!
UPD (in manifest file):
"background": {
"scripts": [ "background.js"]
},
"content_scripts": [
{
"js": [ "content.js" ],
"matches": [ "<all_urls>" ],
"all_frames": true,
"run_at": "document_end"
}
],
UPD 2. This snippet is from my working extension manifest:
"web_accessible_resources": [
"main.js",
"style.css",
"options/options.css",
"options/options.js"
]
Your extension folder look like:
Your manifest.json file:
{
"name": "Bootstrap Grid for any Website",
"version": "1.1.0",
"manifest_version": 2,
"description": "Quickly toggle a Bootstrap Grid for any website. Easy to use, easy success.",
"browser_action": {
"default_icon": "src/icon48.png"
},
"background" : {
"scripts" : [
"background.js"
]
},
"permissions": [
"tabs",
"<all_urls>"
],
"web_accessible_resources":[
"src/content",
"src/content_temp",
"libs/jquery.js"
]
}
background.js:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, {
file: "libs/jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "src/content.js"
});
});
});
chrome.runtime.onMessage.addListener(function(message){
if(message.info !== 1) return;
chrome.tabs.executeScript(null, {
file: "src/content_temp.js"
});
});
And your send_value.js file I put into content.js:
window.addEventListener('resize', function (e) {
// here you send message to background.js
var message = {info: 1}
chrome.runtime.sendMessage("", message);
});
function devTool() {
As for me, it works fine! :-)

Chrome never reads key NativeMessagingHosts to run native messaging

I have a chrome extension that I'm developing. Using process monitor, I'm filtering on NativeMessagingHosts in the path and it never gets hit on the registry. Here is my REG file:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\Software\Google\Chrome\NativeMessagingHosts\com.app.native.messaging.ChromeMessageRepeater]
#="C:\\Prototypes\\Plugins\\DG2\\com.app.native.messaging.ChromeMessageRepeater.json"
Now, here is the JSON for the plugin manifest:
{
"manifest_version": 2,
"name": "--------- 2.0",
"description": "",
"version": "2.0",
"content_scripts" :[
{
"matches": ["*://*/*"],
"run_at": "document_idle",
"js": ["jquery-1.12.2.min.js", "dg2.js"]
}
],
"background": {
"page": "back.html",
"persistent": true
},
"permissions": [ "nativeMessaging", "alarms", "tabs", "activeTab", "*://*/*"]
}
here is the json for the native messaging app
{
"name": "com.app.native.messaging.ChromeMessageRepeater",
"description": "",
"path": "ChromeMessageRepeater.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://lpldkcbggjamnjbndpddgoikgeabfapb/"
],
"permissions": [
"nativeMessaging"
]
}
Any idea why the registry key is never read? When trying to use the plugin, the Port is never opened if I use chrome.runtime.connectNative nor if I used chrome.runtime.sendNativeMessage
EDIT:
function postMessage2(url, dom) {
var port = chrome.runtime.connectNative("com.app.native.messaging.ChromeMessageRepeater");
if(typeof chrome.runtime.lastError !== 'undefined') console.log(chrome.runtime.lastError.message);
port.onMessage.addListener(function(msg) {
console.log("Received" + msg);
});
port.onDisconnect.addListener(function() {
console.log("Disconnected");
});
try {
port.postMessage({ text: url + ';' + dom });
}
catch(ex) {
console.error(ex);
}
};
function postMessage(url, dom) {
chrome.runtime.sendNativeMessage("com.app.native.messaging.ChromeMessageRepeater", { text: url + ';' + dom });
if(typeof chrome.runtime.lastError !== 'undefined') {
console.log(chrome.runtime.lastError.message);
}
};
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.type === "native"){
postMessage2(request.url, request.dom);
sendResponse({ result: true });
}
}
);

Using Google Chrome ttsengine for speech input

I am developing a chrome extension and using tts and ttsengine for speech i/o. But my extension have my chrome to crash without a useful error code (Chrome quits unexpectedly with Process: Google Chrome [888])
When I call the javascript method chrome.experimental.speechInput.start(function(){}) chrome crashes.
I tried another extension provided by google which is Speech Recognizer and it works well, also the speech input in google.com works well. Experimental flag has been set.
Is there any additional permission to give or any other procedure to make speech-to-text work?
My manifest.json:
{
"name": "my_extension",
"version": "0.1",
"manifest_version": 2,
"description": "my description",
"icons": {
"16": "icon16.png",
"128": "icon128.png"
},
"app": {
"launch": {
"local_path": "/twitter/index.html"
}
},
"offline_enabled": true,
"permissions": [
"experimental",
"unlimitedStorage",
"https://api.twitter.com/*",
"ttsEngine",
"tts"
],
"tts_engine": {
"voices": [{
"lang": "de",
"event_types": ["end"]
}]
}
}
My .js file:
function startSpeechInput() {
chrome.experimental.speechInput.onError.addListener(recognitionFailed);
chrome.experimental.speechInput.onResult.addListener(recognitionSucceeded);
chrome.experimental.speechInput.onSoundEnd.addListener(recognitionEnded);
chrome.experimental.speechInput.isRecording(function (recording) {
if (!recording) {
chrome.experimental.speechInput.start({ 'language': 'en-US' }, function(){
//TODO
}
console.log("Voice recognition started!");
});
}
else {
console.log('Pressed Record while it is already recording. Do nothing...');
}
});
}
It worked for me with your content after some changes.
Screenshot
Manifest.json:
{
"name": "my_extension",
"version": "0.1",
"manifest_version": 2,
"description": "my description",
"icons": {
"16": "icon.jpg",
"128": "icon.jpg"
},
"app": {
"launch": {
"local_path": "index.html"
}
},
"background":{
"scripts": ["background.js"]
},
"offline_enabled": true,
"permissions": [
"experimental",
"unlimitedStorage",
"https://api.twitter.com/*",
"ttsEngine",
"tts"
],
"tts_engine": {
"voices": [{
"lang": "de",
"event_types": ["end"]
}]
}
}
index.html
<html>
<head>
<script src="index.js">
</script>
</head>
<body>
</body>
</html>
index.js
function recognitionFailed(error) {
alert("Speech input failed: " + error.code);
}
function recognitionSucceeded(result) {
alert("Recognized '" + result.hypotheses[0].utterance + "' with confidence " + result.hypotheses[0].confidence);
}
function startSpeechInput() {
chrome.experimental.speechInput.onError.addListener(recognitionFailed);
chrome.experimental.speechInput.onResult.addListener(recognitionSucceeded);
chrome.experimental.speechInput.onSoundEnd.addListener(function (){
console.log("started");
});
chrome.experimental.speechInput.isRecording(function (recording) {
if (!recording) {
chrome.experimental.speechInput.start({ 'language': 'en-US' }, function(){
console.log("Voice recognition started!");
});
}
else {
console.log('Pressed Record while it is already recording. Do nothing...');
}
});
}
startSpeechInput();
background.js
function dummy() {
}