Chrome extension not accessing target page DOM - javascript

After reviewing the suggested responses, I was not able to resolve the following issue:
My javascript is not accessing the page DOM, but it is running.
Manifest.json
{
"name": "Clicky",
"version": "1.0",
"background": { "scripts": ["jquery.js", "clickclickboom.js"] },
"permissions": [
"tabs", "http://*/*"
],
"browser_action": {
"name": "Find all links",
"icons": ["icon.jpg"]
},
"manifest_version": 2
}
clickclickboom.js
alert("script runs");
function clicky() {
alert ("clicky got called");
jQuery(".testClass").find("a");
}
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(
null, {code: clicky()});
});
Both alerts pop up but when I debug, I see the extension accessing the background.html DOM but not the targeted pages' DOM.
Any help would be greatly appreciated, thank you in advance!

In your chrome.tabs.executeScript(), the code property must be a string containing the code.
What's happening currently with your code is: clicky() is executed, which returns undefined, which basically is making your executeScript a no-operation call...
One thing you can do is use clicky.toString() though I don't personally recommend it! In this case, the alert ("clicky got called") may work (if you are lucky). The next line will not work because jQuery is not defined in the content script. Your inclusion of jquery is limited to background page.
From your code, it seems you are not really familiar with chrome extension's architecture, so I suggest you start with http://code.google.com/chrome/extensions/getstarted.html

Related

Object.keys not working in extension but working in console [duplicate]

So there is a new API, proposed as a W3C standard, but to use it you need to have this extension for now.
The extension adds an additional document key named monetization, which you can access with document.monetization. And also, the website must have a payment pointer to be able to access it.
I'm trying to access it with an extension I am developing, but I get an undefined error. Here's my manifest.json
{
"manifest_version": 2,
"name": "Test Ext",
"description": "Test Description",
"version": "1.0.0",
"browser_action": {
"default_icon": "icon.png",
"default_pop": "popup.html",
"default_title": "A popup will come here."
},
"permissions": ["activeTab"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["app.js"]
}
]
}
and in my app.js, I made a simple script to check if document.monetization is loaded.
const tid = setInterval( function () {
if (document.monetization === undefined) return;
console.log('Accessible', document.monetization);
clearInterval( tid );
}, 100 );
But it's not working. How do you manage this?
As we can see in the source code of that extension document.monetization is an expando property on a standard DOM document interface, this property is not a part of DOM, it's essentially a JavaScript object so it's not accessible directly from a content script which runs in an isolated world - all JavaScript objects/variables/expandos are isolated so the page scripts can't see the JS objects of content scripts and vice versa.
In Chrome to access such an expando property you need to run the code in page context and then use standard DOM messaging via CustomEvent to coordinate the code in page context and the content script as shown in a sibling answer in the same topic.
In Firefox you can use wrappedJSObject e.g. document.wrappedJSObject.monetization

Can't access content of page when attempting to add Dom to chrome-extension:// URL

My chrome extension spawns a temp .html page. I want to manipulate the DOM of the sample.html page that was created, but can't. I can manipulate the DOM for any other page without issue. The problem seems to be with the fact my temp .html page resides within chrome-extension://
Error Message:
Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "chrome-extension://123/sample.html?id=100". Extension manifest must request permission to access this host.
Note: for simplicity sake I provided sample code that exhibits the same Error. Once loaded I can use the key combo to inject a div and some text into any webpage (Mac-> Cmd+Shift+P or PC Ctrl+Shift+P)
I've tried adding all possible permissions and even web_accessible_resources to the manifest.json. (I don't believe this to be the issue). I've tried different ways to inject the code into the sample.html by calling out the specific tabId, activeTab or even setting the tabId to null within the background file. I've read through stackoverflow, googled and looked around but came up short.
manifest.json
{
"manifest_version": 2,
"name": "sample1",
"description": "sample1",
"version": "0.0.1",
"browser_action":
{
"default_title": "sample"
},
"commands":
{
"saveImageCommand":
{
"suggested_key":
{
"default": "Ctrl+Shift+Z",
"mac": "Command+Shift+Z"
},
"description": "Toggle Save Image"
},
"playback":
{
"suggested_key":
{
"default": "Ctrl+Shift+P",
"mac": "Command+Shift+P"
},
"description": "load player Image"
}
},
"permissions": [
"tabs",
"activeTab",
"storage",
"<all_urls>",
"*://*/*"
],
"background":
{
"persistent": false,
"scripts": ["background.js"]
}
,
"web_accessible_resources": [
"chrome-extension://*/sample.html?id=*"
]
}
background.js
chrome.commands.onCommand.addListener(function(command) {
if (command === 'saveImageCommand') {
capturecurrent();
}
if (command === 'playback') {
chrome.tabs.executeScript(null, {
code: 'var divNode = document.createElement("div");divNode.setAttribute("id", "video1Div");var instructions = document.createTextNode("testing");divNode.appendChild(instructions);document.body.appendChild(divNode)'
});
}
});
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.captureVisibleTab(function(screenshotUrl) {
var viewTabUrl = chrome.extension.getURL('sample.html')
chrome.tabs.create({ url: viewTabUrl });
});
});
sample.html
<html>
<head></head>
<body>
<div id="firstDiv">firstDiv</div>
</body>
</html>
Expected Results:
For me to interact directly with the DOM on the temp sample.html page.
Note:
I don't want to build out buttons for DOM manipulation directly within the sample.html page. That defeats the purpose of this exercise. Esp since I want to use shortcut key combos to call this DOM manipulation (Mac-> Cmd+Shift+P or PC Ctrl+Shift+P)
Actual Results:
I am able to interact with the DOM on any normal website using the shortcut key combo but not the sample.html that URL starts with chrome-extension://

Context menus not working firefox add-on WebExtensions

I'm trying to add a context menu to my firefox add-on using the WebExtensions API. I need the background script to listen to a click on the menu item and send a message to the content script.
This is what I have:
manifest.json
{
"manifest_version": 2,
"name": "MyExt",
"version": "0.0.1",
"description": "Test extension",
"icons": {
"48": "icons/icon-48.png"
},
"applications": {
"gecko": {
"id": "myext#local",
"strict_min_version": "45.0"
}
},
"permissions": ["contextMenus"],
"background": {
"scripts": ["background-scripts.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-script.js"]
}
]
}
background-scripts.js
chrome.contextMenus.create({
id: "clickme",
title: "Click me!",
contexts: ["all"]
});
browser.contextMenus.onClicked.addListener(function(info, tab) {
console.log("Hello World!");
sendMessage(info, tab);
});
function sendMessage(info, tab) {
chrome.tabs.query(
{active: true, currentWindow: true },
function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, "Test message from background script.");
}
);
}
content-script.js
browser.runtime.onMessage.addListener(function(msg) {
console.log(msg);
});
The menu item is being created, but the messages are never displayed (I'm checking both the Web and Browser Console). Since the click event is not working, the message is not sent either.
I'm following this example from MDN, which does not work. It also creates the menu items, but they do nothing, which makes me think that something changed in the API and MDN didn't bother to update the documentation.
Any ideas? Thanks.
Your code works as written:
I strongly suspect that your issue is either of:
You are testing using a version of Firefox prior to Firefox 48. Firefox 48 is in Beta. The contextMenus "Browser compatibility" section clearly states that the first version in which it is functional is Firefox 48. The WebExtensions API is still in development. In general, you should be testing against Firefox Developer Edition, or Firefox Nightly. You can use earlier versions if all the APIs you are using are indicated to be working in an earlier version. However, if you experience problems, you should test with Nightly. I suspect that this is your most likely issue as you indicated that the contextMenus example code was not doing anything.
You have not navigated to an actual webpage. Your content-script.js is only loaded into pages that match one of the supported schemes: that is, "http", "https", "file", "ftp", "app". It is not loaded in about:* pages. If this was your issue, you would have had partial functionality from the contextMenus example code. In addition, using your code, the Browser Console would have, after a delay, generated an error message:
Error: Could not establish connection. Receiving end does not exist.
A note on your code:
Note, your sendMessage() function is, potentially, overly complex. You are searching for the active tab when the tabs.Tab object for the tab in which the context menu item was selected was already passed to your function as one of the arguments. A shorter version could be:
function sendMessage(info, tab) {
chrome.tabs.sendMessage(tab.id, "Test message from background script.");
}
I would be interested to know if you have encountered a situation where you needed to search for the active tab rather than use the tabs.Tab object provided by the context menu listener.

chrome.storage between popup and browser action window

I'm writing a chrome extension and I want to manage all of the data/variables with chrome storage. From what I understand, I should be able to use chrome.storage across my extension.
I want to set something in browser_action script and then access it in the window created by the background script. The HTML and JS files all have corresponding names.
This is what I have tried with no luck:
//manifest.json
{
"manifest_version": 2,
"name": "extension",
"description": "my extension",
"version": "0.1",
"permissions": [
"tabs",
"storage"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": {
"38": "images/icon38.png"
},
"default_popup": "settings.html"
}
}
//background.js
chrome.windows.create({'url': chrome.extension.getURL("newPage.html"),'type': "detached_panel",'focused': true}, function(){
//created newPage.html which has newPage.js
});
//setting.js
document.addEventListener('DOMContentLoaded', function(){
chrome.storage.local.set({'enabled': 'TRUE'});
});
//newPage.js
chrome.storage.local.get('enabled', function(result){
document.getElementById("myId").innerHTML += "<br>script loaded... and status: " + result.enabled;
});
When I do this, newPage.html displays "script loaded... and status: undefined".
Even with it being asyncronous, the storage value should be populated on running the script a second time, right?
I may just be using this incorrectly. If that's the case, what's the correct way to set something with chrome storage to access in my new window?
Any help would be appreciated!
I think that your newPage.html is asking for the value of 'enabled' before it's been set by the event handler in settings.html, which only executes after you've actually opened the browser popup. So this is why it's undefined. Open the popup and you should see that it's defined.

How can I run this script when the tab reloads (chrome extension)?

So i'd like to run a script when the tab reloads in a specified URL. It almost works, but actually id doesn't :)
This is my manifest file:
{
"manifest_version": 2,
"name": "Sample Extension",
"description": "Sample Chrome Extension",
"version": "1.0",
"content_scripts":
[
{
"matches": ["http://translate.google.hu/*"],
"js": ["run.js"]
}
],
"permissions":
[
"activeTab",
"tabs"
],
"browser_action":
{
"default_title": "Sample",
"default_icon": "icon.png"
}
}
and this is run.js:
chrome.tabs.onUpdated.addListener(
function ( tabId, changeInfo, tab )
{
if ( changeInfo.status === "complete" )
{
chrome.tabs.executeScript( null, {file: "program.js"} );
}
}
);
The programs.js just alerts some text (yet). When I put an alert to the first line of the run.js, it alerts, but when I put it in the if, it doesn't. I can't find the problem. Did I type something wrong?
Assuming that http://translate.google.hu/* pages are the ones you wish to inject code into on reload, you would have to go about it in a slightly different way. Currently you are always injecting code into those pages (without the permission to do so, no less) and then trying to use the chrome.tabs api inside that content script, which you can't do. Instead, we will put the listener in a background page and inject the code only on a page refresh, like you want. First the manifest:
{
"manifest_version": 2,
"name": "Sample Extension",
"description": "Sample Chrome Extension",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"permissions":[
"http://translate.google.hu/*", "tabs"
]
}
background.js
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
if (tab.url.indexOf("http://translate.google.hu/") > -1 &&
changeInfo.url === undefined){
chrome.tabs.executeScript(tabId, {file: "program.js"} );
}
});
This will listen for the onUpdated event, checks if it is one of the url's that we want to inject into, and then it checks if the page was reloaded. That last step is accomplished by checking if changeInfo.url exists. If it does, then that means that the url was changed and thus not a refresh. Conversely, if it doesn't exist, then the page must have only been refreshed.
2021
If you want to detect reload from background.js in manifest 3 (maybe also 2), chrome.tabs.onUpdated approach didn't work for me :/ It was invoked too many times.
That what worked for me in the end!
// --- On Reloading or Entering example.com ---
chrome.webNavigation.onCommitted.addListener((details) => {
if (["reload", "link", "typed", "generated"].includes(details.transitionType) &&
details.url === "http://example.com/") {
codeAfterReload();
// If you want to run only when the reload finished (at least the DOM was loaded)
chrome.webNavigation.onCompleted.addListener(function onComplete() {
codeAfterReloadAndFinishSomeLoading();
chrome.webNavigation.onCompleted.removeListener(onComplete);
});
}
});
For more transition types: https://developer.chrome.com/docs/extensions/reference/history/#transition_types
good luck :)
content_scripts are run at every page (re)load, so it's best to just use those to detect it.
This way you also don't risk running any code in the background before your content_script is ready to receive any message.

Categories