I'm using knockoutjs in my google chrome app. To be able to use knockout, I have to define the real application.html as sandox page and include it as an iframe in a dummy container. Application structure is as follows:
- container.html
|
+-- application.html as iframe
|
+-knockout and application.js
Iframe is defined as follows:
<iframe src="application.html" frameborder="0"
sandbox="allow-same-origin allow-scripts" ></iframe>
Running
document.getElementsByTagName("iframe")[0]
in inspect tool on container.html throws following error.
Sandbox access violation: Blocked a frame at "chrome-extension://hllbklabnppjkmnngfanldbllljfeaia"
from accessing a frame at "chrome-extension://hllbklabnppjkmnngfanldbllljfeaia".
The frame being accessed is sandboxed and lacks the "allow-same-origin" flag.
How can i access the iframed document from it's parent?
Do something like this:
manifest.json
"sandbox": {
"pages": ["my_ui.html"]
}
my_ui.html
<script type="text/javascript" src="knockout-1.2.3.4.js"></script>
<script type="text/javascript" src="my_ui.js"></script>
my_ui.js
this.onSomethingChange = function() {
window.top.postMessage(
{ command: 'please-do-something', myArgument: this.myArgument() }, '*');
};
container.html
<script type="text/javascript" src="container.js"></script>
<iframe id="knockoutFrame" src="my_ui.html"></iframe>
container.js
window.addEventListener('message', function(event) {
var kocw = document.getElementById('knockoutFrame').contentWindow;
var anotherContentWindow = // etc.
var dest;
if (event.source == kocw) {
// The knockout iframe sent us a message. So we'll forward it to our
// app code.
dest = anotherContentWindow;
}
if (event.source == anotherContentWindow) {
// Our app code is responding to the knockout message (or initiating
// a conversation with that iframe). Forward it to the knockout code.
dest = kocw;
}
if (dest == null) {
console.log('huh?');
}
// This makes container.js like a gatekeeper, bouncing valid messages between
// the sandboxed page and the other page in your app. You should do
// better validation here, making sure the command is real, the source
// is as expected for the kind of command, etc.
dest.postMessage(event.data, '*');
}
Your statement "I have to define the real application.html as sandbox page and include it as an iframe in a dummy container" is probably not what you wanted. The idea is to sandbox the smallest possible thing, message out to the gatekeeper page that validates the messages, and have the gatekeeper forward the narrow messages to your un-sandboxed application logic. If you just stuff everything into the sandbox, you're defeating the purpose of the sandbox.
Disclaimer: I haven't carefully examined this code from a security perspective. You'll want to assume that hostile messages are coming from the sandbox (or from elsewhere, for that matter), and do what you can to address that threat.
Found out the culprit. This is my proxy.js, which is included by the container.html, used as a bridge to transfer the messages between the application iframe and the background.js. Following part is the one that listens for the messages originated from the iframe.
window.addEventListener("message",
function(evt){
console.log(evt); <= this is the problem
var iframe = document.getElementById("application").contentWindow; <= not this one
if (evt.source == iframe) {
return chrome.runtime.sendMessage(null, evt.data);
}
}
);
I didn't think that console.log would be the causing the problem. Instead i was suspecting from the document.getElem.. line. Because trying to run that code in inspect window of the application was throwing the same error.
But it seems that console.log (console seems to belong to container.html's scope) accesses some internals of event object that are not meant to be accessible out of the iframe's scope(which explains why i get the same error in inspect console). Removing the console.log line solved this problem for me.
Related
I'm trying to start a youtube video when a modal is opened and not progress to the next page until it is completed.
My script below works in Chrome but produces this error in Firefox and Edge.
Failed to execute 'postMessage' on 'DOMWindow': The target origin
provided ('https://www.youtube.com') does not match the recipient
window's origin ('http://example.com').
Javascript
<script src="http://www.youtube.com/player_api"></script>
<script>
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('Thank you for watching - Click OK to see your results');
}
}
</script>
<script language="JavaScript">
$(document).ready(function() {
$('#post_form').submit(function() { // catch the form's submit event
$("#adModal").modal("show");
var time = $('#adtime').val();
//startCountdownTimer(time) ;
// create youtube player
var player;
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: 'EF-jwIv1w68',
host: 'http://www.youtube.com',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
});
});
</script>
I have reviewed this question/answer but cannot seem to get it working with my code by amending the http / https.
I think that the error message is a little bit misleading, as it has nothing to do with your actual host, but is more about how resources from youtube.com are referenced on the page.
There are two things I would suggest in order to get rid of this error message. (At least these were working in my case.)
First and foremost you should reference the IFrame Player API script via https. When called with http, YouTube redirects that script request automatically to it’s https counterpart, so if you reference the script directly from https, that eliminates this extra redirect. But most importantly, in case your production environment ever goes to https, it won’t load that script over http, but will throw a “Blocked loading mixed active content” error.
According to my tests this change alone would already magically solve the issue. However in case you would prefer to leave that on http, there is this other thing:
Reading through the Loading a Video Player and the Supported Parameters sections of the API docs, there is no mention about the host parameter at all. In fact when I removed that line from the Player parameters I didn't receive the error message any more. Also, interestingly, when I set host literally to http://www.example.com, the error message reads: The target origin provided (‘http://www.example.com’) does not match the recipient window’s origin ….) Therefore I think the host parameter should not be set by the client.
Sidenote: If you have a look at the contents of https://www.youtube.com/player_api, you will see this statement: var YTConfig = {'host': 'http://www.youtube.com'};. To me it means that http://www.youtube.com is some kind of a default for host anyways, so even if you go and set it in the client code, you could try to set it to https://www.youtube.com.
Long story short, try to use <script src="https://www.youtube.com/player_api"></script> and comment out the host. This is my 2 cents.
The solution was simple, although I do not know why. By removing the api from the modal it worked fine. Within the modal it wouldn't.
In my case (similar to the selected answer here Youtube API error - Failed to execute 'postMessage' on 'DOMWindow':) It came down the to the fact that the video was not visible on the page at the time Player was instantiated.
In my Case "widget_referrer" was missing. If nothing works for you, try
widget_referrer :window.location.href
other possible properties one might miss are
origin:window.location.href,
enablejsapi:1,
My website is configured without the www and the youtube link was with www that's why i was getting this error.
Try to make it similar, I removed www from my youtube, and it works.
I'd like to write an extension for Thunderbird that modifies the message display (e.g. insert/replace text/markup/image).
Unfortunately, the documentation is lacking (due to recent changes?).
https://developer.mozilla.org/en-US/docs/Mozilla/Thunderbird/Thunderbird_extensions
is outdated
https://developer.thunderbird.net/
does not have useful examples (yet)
https://thunderbird-webextensions.readthedocs.io/
no examples either
Some examples can be found at
https://github.com/thundernest/sample-extensions
Building on https://github.com/thundernest/sample-extensions/tree/master/messageDisplay
I've modified background.js
browser.messageDisplay.onMessageDisplayed.addListener((tabId, message) => {
console.log(`Message displayed in tab ${tabId}: ${message.subject}`);
console.log(message.id);
browser.messages.getFull(message.id).then((messagepart) => {
console.log(messagepart);
body = messagepart['parts'][0]['parts'][0]['body'];
console.log(body);
body += "modified!";
console.log(body);
});
browser.windows.getCurrent().then((window)=>{
console.log(window.type);
});
browser.tabs.getCurrent().then((tab)=>{
console.log("tab",tab);
});
});
which gives me the message body (using magic indexes) but expectedly, the change is not reflected in the message display.
The window type returned is normal, not messageDisplay.
The tab is undefined despite adding permissions
"permissions": [
"messagesRead",
"activeTab",
"tabs",
"tabHide"
],
but I assume that's because the script is running as background.
So I'd need a script running on the content / access to the tab and then some hints on how to modify the displayed message content (I do not want to modify the message).
Where would I find the equivalent documentation to
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts
specific to Thunderbird?
Specifying content_scripts in manifest.json causes "Error: Error reloading addon messageDisplay#sample.extensions.thunderbird.net: undefined".
executeScript() from background does not seem to work either, even with tabId specified.
This was not possible to do when you wrote your question, the API for modifying displayed messages was missing.
As of this writing (September 2020), the browser.messageDisplayScripts API landed a few days ago, see bug 1504475 and related patch for examples. It works as follows: You can register your content script (to modify the displayed messages) like this
let myPromise = browser.messageDisplayScripts.register({
css: [{
file: "/style.css",
}],
js: [{
file: "/content_script.js",
}],
});
And you can later unregister with
myPromise.then((script) => { script.unregister(); });
You need to register the script just once for all messages (you do not need a listener that would load it each time a message is displayed).
Note that your manifest.json needs to include the messagesModify permission for this to work.
The new API will be in Thunderbird version 82, so if I understand the release process correctly it should be in stable version 88 (unless it is backported before that). You can try it already (v82 is the current EarlyBird).
Documentation https://thunderbird-webextensions.readthedocs.io/en/68/tabs.html#getcurrent
says:
May be undefined if called from a non-tab context (for example: a background page or popup view).
Since the background.js is not called from a tab context the tab is undefined.
I want to get the URL from an iframe when the user redirects by clicking links in the iframe. The source of the iframe is not the same as the web application.
For example:
<iframe src="startingUrl" class="embed-responsive-item" id="iframe" sandbox="" allowfullscreen</iframe>
I add a load listener on the iframe to detect when the user redirects to other urls in this iframe:
const iframe = document.getElementById("iframe");
iframe.addEventListener("load", (evt) => {
const location = iframe.contentWindow.location;
console.log(location); // this gives me a Location object where I can see the href property
console.log(location.href); // this gives me a SecurityError: Permission denied to get property "href" on cross-origin object, I also tried to get a copy of the object but that doesn't work either.
});
I know what causes this problem and I also know it is not possible. But I need to find a way to get the current URL of the page. If this is a no go then I want that the user who uses this web application can copy the url of the iframe and put it in an input field.
Now they can do "View frame source" in chrome and This frame: view frame source or info in Firefox. But this is too complicated for the user. Is there a way they can see the URL in the iFrame or a way for the user to get the URL simpler.
The site in the iFrame is not mine.
All help is much appreciated!
Short answer: This is a no go, unless you have the support of the other site in your iframe and they are willing to add the code in #박상수 answer.
Longer answer: You could set up a proxy server to inject the required code to make this work, but then you will run into legal and ethical difficulties, so I am not going to explain how to do that in depth.
Another approach might be to create a browser extension and have your users install that. Again I should point out FaceBook has in the past ran into ethical difficulties taking this approach.
Ultimately their are very good security reasons why the browser stops you doing this and you should probably respect those reasons and not do it.
If you don't see the code below, check the link below.
console.log(iframe.src);
Check out this link
SecurityError: Blocked a frame with origin from accessing a cross-origin frame
let frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
window.addEventListener('message', event => {
// IMPORTANT: check the origin of the data!
if (event.origin.startsWith('http://your-first-site.com')) {
// The data was sent from your site.
// Data sent with postMessage is stored in event.data:
console.log(event.data);
} else {
// The data was NOT sent from your site!
// Be careful! Do not use it. This else branch is
// here just for clarity, you usually shouldn't need it.
return;
}
});
You will want to override the error being automatically thrown:
const iframe = document.getElementById('iframe');
iframe.addEventListener('load', evt => {
const loc = iframe.contentWindow.location;
try{
loc.href;
}
catch(e){
if(e.name === 'SecurityError'){
console.log(iframe.src);
}
}
});
<iframe src='https://example.com' class='embed-responsive-item' id='iframe' sandbox='' allowfullscreen></iframe>
Overview of the problem
I cannot access the DOM of a window that I open programmatically in my chrome extension. I believe this may be due to origin/cross-site scripting restrictions. I have tried to give it the maximal permissions I can, including "<all_urls>", "activeTab" and "tabs"
I also played around with "content_security_policy_" settings but from the documentation I was hoping rather than expecting that to help.
I have a simple extension that runs code when the button is clicked, I want to open a few different tabs (but from different domains) and then access the DOM of each. However, it only seems to work if I'm on a tab of a domain and then I open another tab of the same of domain. Then I can access, for example, window onload of the new tab. I have no luck when it is a different domain.
e.g. if I press the button with activeTab "foo.com" then if it window.opens a new tab "foo.com/something" then I can access the document of that opened tab. But if it was "bar.com" then I wouldn't be able to access "foo.com/something"'s DOM
p.s. please note that executeScripts is used instead of manifest content scripts because it is necessary for my code to work. I must inject at least some of the files there this way, otherwise my code will not work (for reasons that are not completely apparent in the example)
my Question
What's way(s) can I get around this - I mean be able to access the DOM of any tab that I open, regardless of what site is in the active tab when the extension button is pressed in the toolbar?
Should I inject content scripts into a a tab that has been opened with window.open and somehow pass its document to Code.js? If so, how could I go about doing that? Can I somehow pass the document to the background.js? and somehow pass it to the injected Code.js?
If this will work (get around security restrictions) then can these content scripts be injected programatically (I don't know exactly what sites they will be until runtime, so I can't really specify them in the manifest)
or is there some way I can just relax the security restrictions and be able to directly access window.open's returned window's document? (which as I mentioned above currently only works on same-domain sites)
background.js
// this is the background code...
// listen for our browerAction to be clicked
chrome.browserAction.onClicked.addListener(function (tab) {
executeScripts(null, [ // jquery can be inserted here: https://stackoverflow.com/questions/21317476/how-to-use-jquery-in-chrome-extension
{ file: "lib/jquery-3.2.1.js" },
{ file: "lib/kotlin.js" },
{ file: "Code.js" } // don't include it in manifest "content_scripts" because it gives an error about kotlin.js not present that way
])
});
/*
* https://stackoverflow.com/questions/21535233/injecting-multiple-scripts-through-executescript-in-google-chrome
*/
function executeScripts(tabId, injectDetailsArray)
{
function createCallback(tabId, injectDetails, innerCallback) {
return function () {
chrome.tabs.executeScript(tabId, injectDetails, innerCallback);
};
}
var callback = null;
for (var i = injectDetailsArray.length - 1; i >= 0; --i)
callback = createCallback(tabId, injectDetailsArray[i], callback);
if (callback !== null)
callback(); // execute outermost function
}
code flow
background.js
Code.jscalls a function that starts with var w = window.open(url)
then w.addEventListener("load", ...), which is the problem. It only fires if the url belongs to the same domain as the active tab. (onLoad can't be used any-which-way, it never fires that's why I use addEventListener)
notes
I have "manifest_version": 2
I need to inject this way rather than include content scripts in the manifest (I guess I could put the jquery library in the manifest but the others I can't and I prefer to keep all injections together in the "code")
The main problem is that my extension is loading into every iframes on a target webpage. It puts buttons that appear inside the iframes as well. I want them to disappear. The window and document objects are shown as the parent's window and document objects. So it's impossible to check the document location for example because it shows the parent's location instead of the iframe's location.
You could write a user script which uses the #noframes metadata header key and include the user script in to your Jetpack with this user script package for the addon sdk.
Writing user scripts is much easier than writing Page Mods too.
Edit: now (Add-on SDK version 1.11 released) pagemod supports what you are looking for. See the docs and the new attachTo option.
The following information is outdated (can be used if you build against Add-on SDK 1.10 or previous:
Unfortunately pagemod injects your script in all the frames of the page, and not just once per page on the top frame as what you achieve with Chrome's content scripts. Of course, there are workarounds for stopping the execution of the script (see the other answers).
But if you really want to inject your script only once per page, on the top frame, you have to use tabs. With this solution you script only gets injected when it has to.
Bellow I provide and example for porting from pagemod to tabs, keeping all the message reception system with port working. It can easily be modified if you need to not just receive, but also send messages using that same port object. The script gets injected when we are in the domain youtube.com:
Old pagemod way:
var self = require("self");
var pagemod = require("page-mod");
pagemod.PageMod(
{
include: "*.youtube.com",
contentScriptFile: self.data.url("myContentScript.js"),
onAttach: function(worker)
{
worker.port.on("myMessageId", function(payload)
{
console.log("Message received: " + payload);
});
}
});
New tabs way:
var self = require("self");
var tabs = require("tabs");
tabs.on("ready", function(tab)
{
if (tab != undefined && tab.url != undefined && tab.url.split("/")[2] != undefined)
{
var domain = "youtube.com";
var host = tab.url.split("/")[2];
if (host == domain || host.substr(host.length - domain.length - 1) == "." + domain)
{
var worker = tab.attach({ contentScriptFile: self.data.url("myContentScript.js") });
worker.port.on("myMessageId", function(payload)
{
console.log("Message received: " + payload);
});
}
}
});
One workaround is to put something like this in your content script:
if (window.frameElement === null){
// I'm in the topmost window
// Add buttons and things to the page.
}else{
// I'm in an iFrame... do nothing!
}
The content script will still be added to every page, but it's a relatively simple and lightweight check for iFrames.