-1

I have an iframe that loads a list with links from another domain, and I do not want to change the links adress, but I want to change them so they get a onclick function as below. Is this possible at all?

The links in the iframe looks like this.

<div class="flip-entry" id="entry-1ERKvXXUHZHYAA9JLoOz4aau7Y0rTc14h2HucC0CulAM" tabindex="0" role="link">
<div class="flip-entry-info">
<a href="https://docs.google.com/drawings/d/1ERKvXXUHZHYAA9JLoOz4aau7Y0rTc14h2HucC0CulAM/edit?usp=drive_web" target="_blank">
<div class="flip-entry-title">Drawings demo</div>
</a>
</div>
</div>

I want to change all links in the iframe so they looks like this.

<a href="#"  onclick="openInAppBrowser('https://docs.google.com/drawings/d/1ERKvXXUHZHYAA9JLoOz4aau7Y0rTc14h2HucC0CulAM/edit?usp=drive_web');">

I would like to do this with javascript first, but can be jQuery as well.

Thanks for any input!

Claes Gustavsson
  • 5,509
  • 11
  • 50
  • 86

1 Answers1

1

If you have control over the iframe, you can add JavaScript inside the iframe directly. If you don't have control, but is inside your domain, you can run JavaScript from the parent containing the iframe. If is another domain you can't do nothing as it violates browser security.

I'll go with this snippet:

var opena = function(event) {
    openInAppBrowser(this.href);
    event.preventDefault();
    return false; // For jQuery, just in case
};
var as = document.querySelectorAll("a");
for (var i = 0, a; a = as[i]; i++) {
    a.addEventListener("click", opena);
}

document in document.querySelectorAll("a"); needs to be the document you want the links to work on, in this case, the iframe document. There are plenty of ways to access the iframe document, just use the one that fits better with your code: HTML: Getting document from IFrame

Community
  • 1
  • 1
Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64
  • Thanks Jorge. I have control over the iframe, it is on my domain, but not the page I load in it. I have to test your suggestion. – Claes Gustavsson Mar 13 '17 at 10:28
  • Then you can't do nothing. When I mean control over the iframe, I mean the iframe contents (the page you load in it). The browsers prevent this for strong security reasons. If your page is domain.com and you are loading an iframe that conatins domain2.com, the domains are different, so the security policy fires. – Jorge Fuentes González Mar 13 '17 at 10:34
  • @ClaesGustavsson forgot to tag you to get a notification. – Jorge Fuentes González Mar 13 '17 at 10:35